<?php
ini_set('session.cookie_secure', 1);
session_start(['read_and_close' => true]);

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

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

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

session_write_close();

try {



    $stmt3 = $pdo->prepare("
SELECT
    '' AS co_id,
    '' AS id,
    'Date' AS t_date,
    'Doc No' AS t_doc_no,
    'Transfer to' AS acc_name,
    'Tns Type' AS t_type,
    'By' AS depositor,
    '' AS pm_acc_lvl,
    'Amount' AS t_amount,
    '' AS t_status,
    2 AS sort_order
    
 UNION ALL 

 
SELECT
                a.co_id,
                a.id,
                d.t_date,
                d.t_doc_no,
                a.acc_name,
                d.t_type,
                u.acc_name AS depositor,
                p.pm_acc_lvl,
               d.t_credit AS t_amount,
               d.t_status,
              1 AS sort_order
            FROM transactions d
            JOIN accounts u ON d.t_entry_by = u.user_id AND d.co_id = u.co_id
            INNER JOIN accounts a
                ON d.t_cr = a.id
            INNER JOIN account_start_date_track x
                ON x.acc_id = a.id
                JOIN permissions p
        ON (
            a.id = p.pm_acc_id
            OR a.acc_categ = p.pm_acc_categ
        )
        AND p.user_id = :user_id
        AND p.co_id = :coid

WHERE 
p.pm_acc_lvl IN (1,2,6,7) 
AND a.id= :acc_id
AND d.t_status = 'Pending'
  AND d.t_copy = 'O'
  AND a.acc_categ IN ('cash_wallet','bank_wallet','stock')
   AND d.t_type IN ('CTFR','STFR','BNK')
  AND d.t_date >= x.from_date


ORDER BY sort_order DESC, t_date DESC;


    ");
    
    //$search = "%".$acc_srch."%";

    $stmt3->bindParam(':user_id', $user_id, PDO::PARAM_INT);
    
    $stmt3->bindParam(':coid', $coid, PDO::PARAM_INT);
    $stmt3->bindParam(':acc_id', $acc_id, PDO::PARAM_INT);

    $stmt3->execute();

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

    if (!empty($data3)) {

        foreach ($data3 as $row) {

            $t_type = $row['t_type'];
            $entry_by = $row['depositor'];
            
            $pm_acc_lvl = $row['pm_acc_lvl'];

            $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 'Tns Type':

                    $lineStyle = "font-weight:bold;font-size:12px;color:#000;";
                    $dateStyle = "font-weight:bold;font-size:12px;color:#000;";
                    $statusStyle = "font-weight:bold;font-size:12px;color:#000;";
                    //$depositorStyle = "font-weight:bold;font-size:14px;color:transparent;";
                    $depositorStyle = "font-weight:bold;font-size:12px;color:#000;";
                    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;
            $permClass_delete = 0;


            
            if ($pm_acc_lvl =='7' || $pm_acc_lvl =='6' || $pm_acc_lvl =='2'|| $pm_acc_lvl =='1') {
            $permClass = 1;
            }
            
            if (($pm_acc_lvl =='7' || $pm_acc_lvl =='6') || (($pm_acc_lvl =='5'|| $pm_acc_lvl =='4' || $pm_acc_lvl =='3') && $entry_by==$user_id) ) {
            $permClass_delete = 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["t_doc_no"] ?? '') . '
                </td>
                
                <td style="' . $dateStyle . '">
                    ' . htmlspecialchars($row["acc_name"] ?? '') . '
                </td>

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

                <td style="text-align:right; ' . $statusStyle . '">
            ';
            
             if ($t_type === 'Tns Type') {

                echo '
               ';

            } else {

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

            }

 

            if (
                strtolower(trim($row['t_status'] ?? '')) === 'pending'
                && $t_type !== 'DATE'
                && $t_type !== 'Total'
                && $permClass_delete ==1
            ) {

                echo '
                <button 
                    class="btn btn-sm btn-danger delete-btn ml-2"
                    data-doc="' . htmlspecialchars($row['t_doc_no']) . '"
                    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 ==1
            ) {

                echo '

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

                    Confirm

                </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', '.approve-btn', function () {

    let btn = $(this);

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

    $.ajax({

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

        type: 'POST',

        dataType: 'json',

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

        beforeSend: function () {

            btn.prop('disabled', true)
               .text('Confirming...');
               currentRow.find('.delete-btn').remove();
        },

        success: function (response) {

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

//currentRow.find('.delete-btn').remove();
//currentRow.find('.approve-btn').remove();
currentRow.remove();

            } else {

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

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

        error: function () {

            alert('Server error');

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

});

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

    let btn = $(this);

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

    $.ajax({

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

        type: 'POST',

        dataType: 'json',

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

        beforeSend: function () {

            btn.prop('disabled', true)
               .text('Deleting...');
               currentRow.find('.approve-btn').remove();
        },

        success: function (response) {

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

//currentRow.find('.delete-btn').remove();
//currentRow.find('.approve-btn').remove();
currentRow.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>