<?php
include("../classes/manager.class.php");

$m = new Manager();
$output = '';
$payment_no = '';
$payment_date = date('d-m-Y');
$psid = '';
$cpr = '';
$supplier_id = '';
$payment_ref = '';
$payment_type = '';
$amount = '';
$wht_amount = '';
$bank_id = '';
$account_no = '';
$chq_no = '';
$chq_date = '';
$description = '';

if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}

$current_date = date('d-m-Y');
$is_edit = isset($_GET['edit']) && is_numeric($_GET['edit']);

if ($is_edit) {
    $edit_id = $_GET['edit'];
    $record = WhtPaymentTax::GetWhtPaymentTaxSetupById($edit_id);

    if ($record) {
    $payment_no = $record->payment_no;
    $payment_date = date('d-m-Y', strtotime($record->payment_date));
    $psid = $record->psid;
    $cpr = $record->cpr;
    $supplier_id = $record->supplier_id;
    $payment_ref = $record->payment_ref;
    $payment_type = $record->payment_type;
    $amount = $record->expense_amount;
    $wht_amount = $record->wht_amount;
    $bank_id = $record->bank_id;
    $account_no = $record->account_no;
    $chq_no = $record->chq_no;
    $chq_date = !empty($record->chq_date) && $record->chq_date != '0000-00-00' ? date('d-m-Y', strtotime($record->chq_date)) : '';
    $description = $record->description;
}

} else {
    $last = WhtPaymentTax::GetWhtPaymentTaxList("ORDER BY id DESC LIMIT 1");
    if ($last && is_array($last) && count($last) > 0) {
       $payment_no = intval($last[0]->payment_no) + 1;
        $psid = $last[0]->psid;
        $cpr = $last[0]->cpr;
        $chq_no = $last[0]->chq_no;
        $chq_date = date('d-m-Y'); 

    } else {
        $payment_no = 1001;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    extract($_POST);

    $data = [
        'payment_no' => $payment_no,
        'payment_date' => date('Y-m-d', strtotime($payment_date)),
        'psid' => $psid,
        'cpr' => $cpr,
        'supplier_id' => $supplier_name,
        'payment_ref' => $payment_ref,
        'payment_type' => $payment_type,
        'expense_amount' => $amount,
        'wht_amount' => $wht_amount,
        'bank_id' => $bank_name,
        'account_no' => $account_no,
        'chq_no' => $cheque_no,
        'chq_date' => date('Y-m-d', strtotime($cheque_date)),
        'description' => $description,
        'create_date' => date('Y-m-d H:i:s'),
        'created_by' => $_SESSION['sess_userid'],
        'status' => 'active'
    ];

    if ($is_edit) {
        $q = WhtPaymentTax::UpdateWhtPaymentTax($edit_id, $data);
    } else {
        $q = WhtPaymentTax::AddWhtPaymentTax($data);
        if ($q && !empty($payment_ref)) {
            $update = ['wht_paid' => 1];
            ExpenseTaxSetup::UpdateExpenseTaxSetup($payment_ref, $update);
        }
    }

    if ($q) {
        echo "<script>window.location.href='whttax_payment_setup.php?view&success'</script>";
        exit;
    } else {
        $output = '<div class="alert alert-danger">Failed to save record.</div>';
    }
}
?>

<!-- HTML Part -->
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('includes/inc_head.php'); ?>
</head>
<body>
<?php include('includes/inc_top.php'); ?>
<div class="row">
    <div class="col s12 m12">
        <h3><?= $is_edit ? 'Edit' : 'Add' ?> WHT Payment (Expense)</h3>
        <hr>
        <?= $output ?>
        <form method="post">
            <div class="row">
                <div class="col m3">
                    <label>Payment No *</label>
                    <input type="text" name="payment_no" value="<?= $payment_no ?>" readonly />
                </div>
                <div class="col m3">
                    <label>Payment Date *</label>
                    <input type="text" name="payment_date" id="datepicker" value="<?= $payment_date ?>" />
                </div>
                <div class="col m3">
                    <label>PSID</label>
                    <input type="text" name="psid" value="<?= $psid ?>" />
                </div>
                <div class="col m3">
                    <label>CPR</label>
                    <input type="text" name="cpr" value="<?= $cpr ?>" />
                </div>
            </div>

            <div class="row">
                <div class="col m4">
                    <label>Supplier *</label>
                    <select id="supplier_name" name="supplier_name" required>
                        <option value="">Select</option>
                        <?php
                        $suppliers = SupplierSetup::GetSupplierSetupList("WHERE status = 'active'");
                        foreach ($suppliers as $s) {
                            echo "<option value='{$s->id}' " . ($s->id == $supplier_id ? 'selected' : '') . ">{$s->name}</option>";
                        }
                        ?>
                    </select>
                </div>
                <div class="col m4">
                    <label>Payment Ref *</label>
                    <select name="payment_ref" id="purchase_reference_code">
                        <option value="">Select</option>
                        <!-- AJAX loaded via JS -->
                    </select>
                </div>
                <div class="col m4">
                    <label>Payment Type *</label>
                    <select name="payment_type" required>
                        <option value="">Select</option>
                        <option value="bank" <?= $payment_type == 'bank' ? 'selected' : '' ?>>Bank</option>
                        <option value="online" <?= $payment_type == 'online' ? 'selected' : '' ?>>Online</option>
                    </select>
                </div>
            </div>

            <div class="row">
                <div class="col m4">
                    <label>Expense Amount *</label>
                    <input type="text" name="amount" id="amount" value="<?= $amount ?>" />
                </div>
                <div class="col m4">
                    <label>WHT Amount</label>
                    <input type="text" name="wht_amount" value="<?= $wht_amount ?>" />
                </div>
                <div class="col m4">
                    <label>Bank Name</label>
                    <select name="bank_name" id="bank_name">
                        <option value="">Select</option>
                        <?php
                        $banks = BankSetup::GetBankSetupList("WHERE status='active'");
                        foreach ($banks as $b) {
                            echo "<option value='{$b->id}' " . ($b->id == $bank_id ? 'selected' : '') . ">{$b->bank_name}</option>";
                        }
                        ?>
                    </select>
                </div>
            </div>

            <div class="row">
                <div class="col m4">
                    <label>Account No</label>
                    <input type="text" name="account_no" id="account_no" value="<?= $account_no ?>" readonly />
                </div>
                <div class="col m4">
                    <label>Cheque No</label>
                    <input type="text" name="cheque_no" value="<?= $chq_no ?>" />
                </div>
                <div class="col m4">
                    <label>Cheque Date</label>
                    <input type="text" name="cheque_date" id="cheque_date" value="<?= $chq_date ?>" />
                </div>
            </div>

            <div class="row">
                <div class="col m12">
                    <label>Description</label>
                    <textarea name="description"><?= $description ?></textarea>
                </div>
            </div>

            <button class="btn btn-primary" type="submit">Submit</button>
            <a class="btn" href="whttax_payment_setup.php?view&success">Cancel</a>
        </form>
    </div>
</div>

<?php include('includes/inc_js.php'); ?>
<script>
    // Initialize date pickers
    $('#datepicker, #cheque_date').pickadate({ format: 'dd-mm-yyyy' });

    // When supplier is changed
    $('#supplier_name').on('change', function () {
        var supplierId = $(this).val();

        if (supplierId) {
            $('body.container').block({ message: 'Loading...' });

            $.ajax({
                url: 'getFilterExpWhtPayments.php',
                type: 'GET',
                data: { id: supplierId },
                success: function (response) {
                    $('#purchase_reference_code').html(response).trigger('contentChanged');
                    $('body.container').unblock();
                },
                error: function (xhr, status, error) {
                    console.error('Error fetching expense WHT options:', error);
                    $('body.container').unblock();
                }
            });
        } else {
            $('#purchase_reference_code').empty().trigger('contentChanged');
        }
    });

    // Reinitialize the dropdown after content update (for MaterializeCSS users)
    $('#purchase_reference_code').on('contentChanged', function () {
        if (typeof $.fn.material_select === 'function') {
            $(this).material_select(); // Only run if using MaterializeCSS
        }
    });

    // On selecting an expense transaction
    $('#purchase_reference_code').on('change', function () {
        var expenseId = $(this).val();

        if (expenseId) {
            $.get('getExpenseWhtAmountDetails.php', { id: expenseId }, function (res) {
                try {
                    const d = JSON.parse(res);
                    $('#amount').val(d.amount || '');
                } catch (e) {
                    console.error('Invalid JSON from getExpenseWhtAmountDetails:', res);
                    $('#amount').val('');
                }
            });
        } else {
            $('#amount').val('');
        }
    });

    // When bank is selected, auto-fill account number
    $('#bank_name').on('change', function () {
        const bankId = $(this).val();
        if (bankId) {
            $.get('transaction/getBankDetails.php?id=' + bankId, function (data) {
                $('#account_no').val(data);
            });
        } else {
            $('#account_no').val('');
        }
    });
</script>

</body>
</html>
