<?php
session_start();
ini_set('session.cookie_secure', 1);

require_once "../../includes/db.php";

header('Content-Type: application/json');

$user_id = $_SESSION['user_id'] ?? 0;
$coid  = $_SESSION['co_id'];
//$acc_srch     = $_GET['acc_srch'] ?? '';

try {

    $date1 = isset($_GET['date1']) &&
        preg_match('/^\d{4}-\d{2}-\d{2}$/', $_GET['date1'])
        ? $_GET['date1']
        : '0000-00-00';

    $date2 = isset($_GET['date2']) &&
        preg_match('/^\d{4}-\d{2}-\d{2}$/', $_GET['date2'])
        ? $_GET['date2']
        : '0000-00-00';

    $stmt3 = $pdo->prepare("
    
    SELECT
    d.t_date AS sort_date,
        x.min_date,
        d.t_id,
        d.co_id,
        d.t_tt_doc,
        d.t_ct_det,
        d.t_status,

        DATE_FORMAT(d.t_date, '%d-%b-%y') AS t_date,
        DATE_FORMAT(d.t_date, '%d %b%y') AS M_date,

        d.t_doc_no,

        u.acc_name,
        a.acc_name AS depositor,

        d.t_type,

        d.t_credit AS t_amount,
        
        p.pm_acc_lvl,

        1 AS sort_order

    FROM transactions d

    JOIN accounts u
        ON d.t_cr = u.id
    JOIN accounts a
        ON d.t_entry_by = a.user_id
    JOIN trans_period x
    	ON x.co_id= :coid2

    JOIN permissions p
        ON (
            u.id = p.pm_acc_id
            OR u.acc_categ = p.pm_acc_categ
        )
        AND p.user_id = :user_id
        AND p.co_id = :coid

    WHERE
        u.acc_categ IN ('cash_wallet')
        AND d.t_type IN ('csh_close')
        AND p.pm_acc_lvl IN (0,1,2,4,5,6,7,8)
        AND d.t_date BETWEEN :date12 AND :date22
        AND d.co_id = :coid1
        AND u.acc_name LIKE :acc_srch
        AND d.t_status <>'Deleted'

    GROUP BY
        d.t_date,
        d.t_doc_no,
        u.acc_name,
        d.t_type,
        d.t_status



    ORDER BY
        sort_date DESC,
        sort_order,
        t_doc_no
    ");
    
    $search = "%".$acc_srch."%";

    $stmt3->bindParam(':user_id', $user_id, PDO::PARAM_INT);
    
    $stmt3->bindParam(':coid', $coid, PDO::PARAM_INT);
    $stmt3->bindParam(':coid1', $coid, PDO::PARAM_INT);
    $stmt3->bindParam(':coid2', $coid, PDO::PARAM_INT);
    
    $stmt3->bindParam(':acc_srch', $search);


    $stmt3->bindParam(':date12', $date1);
    $stmt3->bindParam(':date22', $date2);


    $stmt3->execute();

    $data3 = $stmt3->fetchAll(PDO::FETCH_ASSOC);

    if (!empty($data3)) {

        foreach ($data3 as $row) {

            $t_type = $row['t_type'];
            
            $pm_acc_lvl = $row['pm_acc_lvl'];
            $mindate = $row['min_date'];
            $tdate = $row['sort_date'];

            $group_date = $row['t_date'];

            $lineStyle = "color:#6c757d;";
            $dateStyle = "color:#6c757d;";
            $statusStyle = "color:#6c757d;";
            $depositorStyle = "color:#6c757d;";

            switch ($t_type) {

                case 'DATE':

                    $lineStyle = "font-weight:bold;font-size:14px;color:transparent;";
                    $dateStyle = "font-weight:bold;font-size:14px;color:#000;";
                    $statusStyle = "font-weight:bold;font-size:14px;color:transparent;";
                    $depositorStyle = "font-weight:bold;font-size:14px;color:transparent;";

                    break;

                case 'Total':

                    $lineStyle = "font-weight:bold;font-size:14px;color:#000;";
                    $dateStyle = "font-weight:bold;font-size:14px;color:#000;";
                    $statusStyle = "font-weight:bold;font-size:14px;color:#000;";
                    $depositorStyle = "font-weight:bold;font-size:14px;color:transparent;";

                    break;

                default:

                    $lineStyle = "font-size:13px;color:#000;";
                    $dateStyle = "font-size:13px;color:#000;";
                    $statusStyle = "font-size:13px;color:#000;";
                    $depositorStyle = "font-size:13px;color:#000;";

                    break;
            }

            $rowClass = '';
            $permClass = 0;

            if ($t_type === 'Total') {
                $rowClass = 'daily-total-row';
            }
            
            if (($pm_acc_lvl =='7' || $pm_acc_lvl =='6' || $pm_acc_lvl =='2'|| $pm_acc_lvl =='1') && $tdate> $mindate ) {
            $permClass = 1;
            }

            echo '

            <tr 
                class="data-row ' . $rowClass . '" 
                data-group="' . htmlspecialchars($group_date) . '"
                style="border:none;">
                
                <td style="' . $dateStyle . '">
                    ' . htmlspecialchars($row["t_date"] ?? '') . '
                </td>

                <td style="' . $dateStyle . '">
                    ' . htmlspecialchars($row["acc_name"] ?? '') . '
                </td>

                <td style="' . $dateStyle . '">
                    ' . htmlspecialchars($row["t_doc_no"] ?? '') . '
                </td>

                <td style="' . $lineStyle . '">
                    ' . htmlspecialchars($t_type) . '
                </td>
                
                <td style="' . $depositorStyle . '">
                    ' . htmlspecialchars($row["depositor"] ?? '') . '
                </td>

                <td style="text-align:right; ' . $statusStyle . '">
            ';

            if ($t_type === 'Total') {

                echo '
                <span class="daily-total-amount">
                    ' . number_format($row["t_amount"], 0, ".", ",") . '
                </span>';

            } else {

                echo number_format($row["t_amount"], 0, ".", ",");

            }

            if (
                 $permClass ==1
            ) {

                echo '

                <button 
                    class="btn btn-sm btn-danger delete-btn ml-2"
                    data-doc="' . htmlspecialchars($row['t_id']) . '"
                    data-type="' . htmlspecialchars($t_type) . '"
                    data-amount="' . floatval($row["t_amount"]) . '">

                    Delete

                </button>';
            }
            
            if (
                strtolower(trim($row['t_status'] ?? '')) === 'pending'
                && $t_type !== 'DATE'
                && $t_type !== 'Total'
                && $permClass ==0
            ) {

                echo '

                <button 
                    class="btn btn-sm btn-warning pend-btn ml-2">

                    Pending

                </button>';
            }

            echo '

                </td>

            </tr>';
        }

    } else {

        echo '
        <tr>
            <td colspan="4" class="text-center text-warning">
                No matching records found.
            </td>
        </tr>';
    }

} catch (PDOException $e) {

    echo '
    <tr>
        <td colspan="4" class="text-center text-danger">
            Error fetching data.
        </td>
    </tr>';

    error_log("Database Error: " . $e->getMessage());
}
?>

<script>

$(document).on('click', '.delete-btn', function () {

    let btn = $(this);

    let doc_no = btn.data('doc');
    let ttype = btn.data('type');

    $.ajax({

        url: '../includes/delete_closecash_transaction.php',

        type: 'POST',

        dataType: 'json',

        data: {
            doc_no: doc_no,
            ttype: ttype
        },

        beforeSend: function () {

            btn.prop('disabled', true)
               .text('Deleting...');
        },

        success: function (response) {

            if (response.status === 'success') {

                let amount = parseFloat(
                    btn.data('amount')
                ) || 0;

                let currentRow = btn.closest('tr');

                let group = currentRow.data('group');

                let totalRow = $(
                    '.daily-total-row[data-group="' + group + '"]'
                ).last();

                let totalSpan = totalRow.find(
                    '.daily-total-amount'
                );

                let currentTotal = parseFloat(
                    totalSpan.text()
                        .replace(/,/g, '')
                        .trim()
                ) || 0;

                // subtract deleted amount
                let newTotal = currentTotal - amount;

                totalSpan.text(
                    newTotal.toLocaleString()
                );

                // remove row
                currentRow.fadeOut(300, function () {

                    $(this).remove();

                    // remove total row if group empty
                    let remainingRows = $('tr[data-group="' + group + '"]')
                        .not('.daily-total-row');

                    if (remainingRows.length === 0) {
                        totalRow.remove();
                    }
                });

            } else {

                alert(response.message || 'Delete failed');

                btn.prop('disabled', false)
                   .text('Delete');
            }
        },

        error: function () {

            alert('Server error');

            btn.prop('disabled', false)
               .text('Delete');
        }
    });

});

</script>