<?php

// Default Column Sortby/Order Filter
$sort = "recurring_invoice_next_date";
$order = "ASC";

// If client_id is in URI then show client Side Bar and client header
if (isset($_GET['client_id'])) {
    require_once "includes/inc_all_client.php";
    $client_query = "AND recurring_invoice_client_id = $client_id";
    $client_url = "client_id=$client_id&";
} else {
    require_once "includes/inc_all.php";
    $client_query = '';
    $client_url = '';
}

// Perms
enforceUserPermission('module_sales');

// Status Filter
if (isset($_GET['status']) && $_GET['status'] == "inactive") {
    $status_filter = "inactive";
    $status_query = "AND recurring_invoice_status = 0";
} else {
    $status_filter = "active";
    $status_query = "AND recurring_invoice_status = 1";
}

$sql = mysqli_query(
    $mysqli,
    "SELECT SQL_CALC_FOUND_ROWS category_id, category_name, client_currency_code, client_id, client_name,
        recurring_invoice_amount, recurring_invoice_created_at, recurring_invoice_currency_code,
        recurring_invoice_discount_amount, recurring_invoice_frequency, recurring_invoice_id,
        recurring_invoice_last_sent, recurring_invoice_next_date, recurring_invoice_number,
        recurring_invoice_prefix, recurring_invoice_scope, recurring_invoice_status,
        recurring_payment_id, recurring_payment_recurring_invoice_id,
        recurring_payment_saved_payment_id FROM recurring_invoices
    LEFT JOIN clients ON recurring_invoice_client_id = client_id
    LEFT JOIN categories ON recurring_invoice_category_id = category_id
    LEFT JOIN recurring_payments ON recurring_payment_recurring_invoice_id = recurring_invoice_id
    WHERE (CONCAT(recurring_invoice_prefix,recurring_invoice_number) LIKE '%$q%' OR recurring_invoice_frequency LIKE '%$q%' OR recurring_invoice_scope LIKE '%$q%' OR client_name LIKE '%$q%' OR category_name LIKE '%$q%')
    AND DATE(recurring_invoice_created_at) BETWEEN '$dtf' AND '$dtt'
    $status_query
    $client_query
    " . clientScopeSql('recurring_invoice_client_id') . "

    ORDER BY $sort $order LIMIT $record_from, $record_to");

$num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()"));

?>

<div class="card">
    <div class="card-header bg-dark py-2">
        <h3 class="card-title mt-2"><i class="fa fa-redo-alt me-2"></i>Recurring Invoices</h3>
        <?php if (lookupUserPermission("module_sales") >= 2) { ?>
        <div class="card-tools">
            <div class="btn-group">
                <button type="button" class="btn btn-primary ajax-modal" data-modal-url="modals/recurring_invoice/recurring_invoice_add.php?<?= $client_url ?>"><i class="fas fa-plus"></i><span class="d-none d-lg-inline ms-2">New Recurring Invoice</span></button>
                <button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown"></button>
                <div class="dropdown-menu">
                    <?php if ($num_rows[0] > 0) { ?>
                        <a class="dropdown-item text-dark ajax-modal" href="#"
                            data-modal-url="<?= buildExportModalUrl('modals/recurring_invoice/recurring_invoice_export.php', ['client_id', 'status', 'q'], ['dtf' => $dtf, 'dtt' => $dtt]) ?>">
                            <i class="fa fa-fw fa-download me-2"></i>Export
                        </a>
                    <?php } ?>
                </div>
            </div>
        </div>
        <?php } ?>
    </div>

    <div class="card-header py-3">
        <form  autocomplete="off">
            <?php if ($client_url) { ?>
                <input type="hidden" name="client_id" value="<?= $client_id ?>">
            <?php } ?>
            <input type="hidden" name="status" value="<?= $status_filter ?>">
            <div class="row g-2 align-items-end">
                <div class="col-sm-4">
                    <div class="input-group">
                        <input type="search" class="form-control" name="q" value="<?php if (isset($q)) {echo strip_tags(escapeHtml($q));} ?>" placeholder="Search Recurring Invoices">
                            <button class="btn btn-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#advancedFilter"><i class="fas fa-filter"></i></button>
                            <button class="btn btn-primary"><i class="fa fa-search"></i></button>
                    </div>
                </div>
                <div class="col-sm-8">
                    <div class="btn-toolbar float-end">
                        <div class="btn-group">
                            <a href="?<?= $client_url ?>status=active" class="btn btn-<?php if ($status_filter == "active"){ echo "primary"; } else { echo "default"; } ?>"><i class="fa fa-fw fa-check me-2"></i>Active</a>
                            <a href="?<?= $client_url ?>status=inactive" class="btn btn-<?php if ($status_filter == "inactive"){ echo "primary"; } else { echo "default"; } ?>"><i class="fa fa-fw fa-ban me-2"></i>Inactive</a>
                        </div>
                    </div>
                </div>
            </div>
            <div class="collapse mt-3 <?php if (isset($_GET['dtf']) && $_GET['dtf'] !== '1970-01-01') { echo "show"; } ?>" id="advancedFilter">
                <div class="row g-3">
                    <div class="col-md-3">
                        <div>
                            <label>Date range</label>
                            <input type="text" id="dateFilter" class="form-control" autocomplete="off">
                            <input type="hidden" name="canned_date" id="canned_date" value="<?= escapeHtml($_GET['canned_date']) ?? '' ?>">
                            <input type="hidden" name="dtf" id="dtf" value="<?= escapeHtml($dtf ?? '') ?>">
                            <input type="hidden" name="dtt" id="dtt" value="<?= escapeHtml($dtt ?? '') ?>">
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>

    <div class="table-responsive">
        <table class="table table-striped table-borderless table-hover mb-0">
            <thead class="text-dark <?php if ($num_rows[0] == 0) { echo "d-none"; } ?> text-nowrap">
            <tr>
                <th>
                    <a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=recurring_invoice_number&order=<?= $disp ?>">
                        Number <?php if ($sort == 'recurring_invoice_number') { echo $order_icon; } ?>
                    </a>
                </th>
                <th>
                    <a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=recurring_invoice_next_date&order=<?= $disp ?>">
                        Next Date <?php if ($sort == 'recurring_invoice_next_date') { echo $order_icon; } ?>
                    </a>
                </th>
                <th>
                    <a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=recurring_invoice_scope&order=<?= $disp ?>">
                        Scope <?php if ($sort == 'recurring_invoice_scope') { echo $order_icon; } ?>
                    </a>
                </th>
                <?php if (!$client_url) { ?>
                <th>
                    <a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=client_name&order=<?= $disp ?>">
                        Client <?php if ($sort == 'client_name') { echo $order_icon; } ?>
                    </a>
                </th>
                <?php } ?>
                <th class="text-end">
                    <a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=recurring_invoice_amount&order=<?= $disp ?>">
                        Amount <?php if ($sort == 'recurring_invoice_amount') { echo $order_icon; } ?>
                    </a>
                </th>
                <th>
                    <a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=recurring_invoice_frequency&order=<?= $disp ?>">
                        Frequency <?php if ($sort == 'recurring_invoice_frequency') { echo $order_icon; } ?>
                    </a>
                </th>
                <th>
                    <a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=recurring_invoice_last_sent&order=<?= $disp ?>">
                        Last Sent <?php if ($sort == 'recurring_invoice_last_sent') { echo $order_icon; } ?>
                    </a>
                </th>
                <th>
                    <a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=category_name&order=<?= $disp ?>">
                        Category <?php if ($sort == 'category_name') { echo $order_icon; } ?>
                    </a>
                </th>
                <th>
                    <a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=recurring_payment_recurring_invoice_id&order=<?= $disp ?>">
                        Auto Pay <?php if ($sort == 'recurring_payment_recurring_invoice_id') { echo $order_icon; } ?>
                    </a>
                </th>
                <th>
                    <a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=recurring_invoice_status&order=<?= $disp ?>">
                        Status <?php if ($sort == 'recurring_invoice_status') { echo $order_icon; } ?>
                    </a>
                </th>
                <th class="text-center">Action</th>
            </tr>
            </thead>
            <tbody>
            <?php

            while ($row = mysqli_fetch_assoc($sql)) {
                $recurring_invoice_id = intval($row['recurring_invoice_id']);
                $recurring_invoice_prefix = escapeHtml($row['recurring_invoice_prefix']);
                $recurring_invoice_number = intval($row['recurring_invoice_number']);
                $recurring_invoice_scope = escapeHtml($row['recurring_invoice_scope']);
                $recurring_invoice_frequency = escapeHtml($row['recurring_invoice_frequency']);
                $recurring_invoice_status = escapeHtml($row['recurring_invoice_status']);
                $recurring_invoice_discount = floatval($row['recurring_invoice_discount_amount']);
                $recurring_invoice_last_sent = $row['recurring_invoice_last_sent'];
                if ($recurring_invoice_last_sent == 0) {
                    $recurring_invoice_last_sent = "-";
                }
                $recurring_invoice_next_date = escapeHtml($row['recurring_invoice_next_date']);
                $recurring_invoice_amount = floatval($row['recurring_invoice_amount']);
                $recurring_invoice_currency_code = escapeHtml($row['recurring_invoice_currency_code']);
                $recurring_invoice_created_at = escapeHtml($row['recurring_invoice_created_at']);
                $client_id = intval($row['client_id']);
                $client_name = escapeHtml($row['client_name']);
                $client_currency_code = escapeHtml($row['client_currency_code']);
                $category_id = intval($row['category_id']);
                $category_name = escapeHtml($row['category_name']);
                if ($recurring_invoice_status == 1) {
                    $status = "Active";
                    $status_badge_color = "success";
                } else {
                    $status = "Inactive";
                    $status_badge_color = "secondary";
                }
                $recurring_payment_id = intval($row['recurring_payment_id']);
                $recurring_payment_recurring_invoice_id = intval($row['recurring_payment_recurring_invoice_id']);
                $recurring_payment_saved_payment_id = intval($row['recurring_payment_saved_payment_id']);

                ?>

                <tr>
                    <td class="text-bold">
                        <a href="recurring_invoice.php?client_id=<?= $client_id ?>&recurring_invoice_id=<?= $recurring_invoice_id ?>">
                            <?= "$recurring_invoice_prefix$recurring_invoice_number" ?>
                        </a>
                    </td>
                    <td class="text-bold"><?= $recurring_invoice_next_date ?></td>
                    <td><?= $recurring_invoice_scope ?></td>
                    <?php if (!$client_url) { ?>
                    <td class="text-bold"><a href="recurring_invoices.php?client_id=<?= $client_id ?>"><?= $client_name ?></a></td>
                    <?php } ?>
                    <td class="text-end font-monospace"><?= numfmt_format_currency($currency_format, $recurring_invoice_amount, $recurring_invoice_currency_code) ?></td>
                    <td><?= ucwords($recurring_invoice_frequency) ?>ly</td>
                    <td><?= $recurring_invoice_last_sent ?></td>
                    <td><?= $category_name ?></td>
                    <td>
                        <?php $sql_saved_payments = mysqli_query($mysqli, "SELECT saved_payment_description, saved_payment_id FROM client_saved_payment_methods WHERE saved_payment_client_id = $client_id");
                        if (mysqli_num_rows($sql_saved_payments) > 0) { ?>
                            <form class="form" action="post.php" method="post">
                                <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                                <input type="hidden" name="set_recurring_payment" value="1">
                                <input type="hidden" name="recurring_invoice_id" value="<?= $recurring_invoice_id ?>">
                                <select class="form-select select2" name="saved_payment_id" onchange="this.form.submit()">
                                    <option value="0">Disabled</option>
                                    <?php
                                        while ($row = mysqli_fetch_assoc($sql_saved_payments)) {
                                            $saved_payment_id = intval($row['saved_payment_id']);
                                            $saved_payment_description = escapeHtml($row['saved_payment_description']);

                                        ?>
                                        <option <?php if ($recurring_payment_saved_payment_id == $saved_payment_id) { echo "selected"; } ?> value="<?= $saved_payment_id ?>"><?= $saved_payment_description ?></option>
                                    <?php } ?>
                                </select>
                            </form>
                        <?php } else { ?>
                            No Cards on File
                        <?php } ?>
                    </td>
                    <td>
                        <span class="p-2 badge text-bg-<?= $status_badge_color ?>">
                            <?= $status ?>
                        </span>

                    </td>
                    <td>
                        <div class="dropdown dropstart text-center">
                            <button class="btn btn-secondary btn-sm" type="button" data-bs-toggle="dropdown">
                                <i class="fas fa-ellipsis-h"></i>
                            </button>
                            <div class="dropdown-menu">
                                <a class="dropdown-item ajax-modal" href="#"
                                    data-modal-url="modals/recurring_invoice/recurring_invoice_edit.php?id=<?= $recurring_invoice_id ?>">
                                    <i class="fas fa-fw fa-edit me-2"></i>Edit
                                </a>
                                <?php if ($status !== 'Active') { ?>
                                    <div class="dropdown-divider"></div>
                                    <a class="dropdown-item text-danger text-bold confirm-link" href="post.php?delete_recurring_invoice=<?= $recurring_invoice_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
                                        <i class="fas fa-fw fa-trash me-2"></i>Delete
                                    </a>
                                <?php } ?>
                            </div>
                        </div>
                    </td>
                </tr>

                <?php
                }
                ?>

            </tbody>
        </table>
    </div>
    <?php require_once "../includes/filter_footer.php";
 ?>
</div>

<?php
require_once "../includes/footer.php";
