<?php
include 'auth_check.php';

requireCreditSaleAccess();

$message = '';
$messageClass = 'success-box';
$today = date('Y-m-d');
$timeNow = date('H:i:s');
$loggedUser = $_SESSION['name'];

function getSelectedCustomer($conn, $customerId) {
    $stmt = $conn->prepare("SELECT * FROM credit_customer WHERE id = ?");
    $stmt->bind_param("i", $customerId);
    $stmt->execute();
    return $stmt->get_result()->fetch_assoc();
}

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

    if ($action === 'add_customer') {
        $customer_name = trim($_POST['customer_name'] ?? '');
        $customer_contact = trim($_POST['customer_contact'] ?? '');

        if ($customer_name === '' || $customer_contact === '') {
            $message = 'Please enter customer name and contact.';
            $messageClass = 'error-box';
        } else {
            $stmt = $conn->prepare("INSERT INTO credit_customer (customer_name, customer_contact, entered_date, entered_time, entered_user) VALUES (?, ?, ?, ?, ?)");
            $stmt->bind_param("sssss", $customer_name, $customer_contact, $today, $timeNow, $loggedUser);
            $stmt->execute();
            $message = 'Customer saved successfully.';
        }
    }

    if ($action === 'update_customer') {
        $customer_id = (int)($_POST['customer_id'] ?? 0);
        $customer_name = trim($_POST['customer_name'] ?? '');
        $customer_contact = trim($_POST['customer_contact'] ?? '');

        if ($customer_id > 0 && $customer_name !== '' && $customer_contact !== '') {
            $stmt = $conn->prepare("UPDATE credit_customer SET customer_name = ?, customer_contact = ? WHERE id = ?");
            $stmt->bind_param("ssi", $customer_name, $customer_contact, $customer_id);
            $stmt->execute();
            $message = 'Customer updated successfully.';
        } else {
            $message = 'Please select a valid customer and fill all fields.';
            $messageClass = 'error-box';
        }
    }

    if ($action === 'delete_customer') {
        $customer_id = (int)($_POST['customer_id'] ?? 0);
        if ($customer_id > 0) {
            $stmt = $conn->prepare("DELETE FROM credit_customer WHERE id = ?");
            $stmt->bind_param("i", $customer_id);
            $stmt->execute();
            $message = 'Customer deleted successfully.';
        } else {
            $message = 'Please select a valid customer.';
            $messageClass = 'error-box';
        }
    }

    if ($action === 'attach_customer') {
        $bill_number = trim($_POST['bill_number'] ?? '');
        $customer_id = (int)($_POST['selected_customer_id'] ?? 0);

        if ($bill_number === '' || $customer_id <= 0) {
            $message = 'Please search a bill and select a customer.';
            $messageClass = 'error-box';
        } else {
            $sellingStmt = $conn->prepare("SELECT * FROM selling_data WHERE bill_number = ? LIMIT 1");
            $sellingStmt->bind_param("s", $bill_number);
            $sellingStmt->execute();
            $bill = $sellingStmt->get_result()->fetch_assoc();

            $customer = getSelectedCustomer($conn, $customer_id);

            if ($bill && $customer) {
                $attachAmount = 0.00;
                $status = $bill['balance_amount'] < 0 ? 'Pending' : 'Settled';
                $actionType = 'Attach';

                $stmt = $conn->prepare("INSERT INTO credit_sale_data (bill_number, total_amount, received_amount, balance_amount, total_discount, status, customer_name, customer_contact, payable_amount, action_type, bill_date, bill_time, entered_date, entered_time, entered_user) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->bind_param(
                    "sddddsssdssssss",
                    $bill['bill_number'],
                    $bill['total_amount'],
                    $bill['received_amount'],
                    $bill['balance_amount'],
                    $bill['total_discount'],
                    $status,
                    $customer['customer_name'],
                    $customer['customer_contact'],
                    $attachAmount,
                    $actionType,
                    $bill['entered_date'],
                    $bill['entered_time'],
                    $today,
                    $timeNow,
                    $loggedUser
                );
                $stmt->execute();
                $message = 'Customer attached to bill successfully.';
            } else {
                $message = 'Bill or customer not found.';
                $messageClass = 'error-box';
            }
        }
    }

    if ($action === 'pay_credit') {
        $bill_number = trim($_POST['bill_number'] ?? '');
        $payable_amount = (float)($_POST['credit_payable'] ?? 0);

        if ($bill_number === '' || $payable_amount <= 0) {
            $message = 'Please enter a valid payable amount.';
            $messageClass = 'error-box';
        } else {
            $sellingStmt = $conn->prepare("SELECT * FROM selling_data WHERE bill_number = ? LIMIT 1");
            $sellingStmt->bind_param("s", $bill_number);
            $sellingStmt->execute();
            $bill = $sellingStmt->get_result()->fetch_assoc();

            if ($bill) {
                $newReceived = (float)$bill['received_amount'] + $payable_amount;
                $newBalance = (float)$bill['balance_amount'] + $payable_amount;

                $up = $conn->prepare("UPDATE selling_data SET received_amount = ?, balance_amount = ? WHERE bill_number = ?");
                $up->bind_param("dds", $newReceived, $newBalance, $bill_number);
                $up->execute();

                $customerStmt = $conn->prepare("SELECT customer_name, customer_contact FROM credit_sale_data WHERE bill_number = ? AND customer_name <> '' ORDER BY id DESC LIMIT 1");
                $customerStmt->bind_param("s", $bill_number);
                $customerStmt->execute();
                $customer = $customerStmt->get_result()->fetch_assoc();
                $customerName = $customer['customer_name'] ?? '';
                $customerContact = $customer['customer_contact'] ?? '';

                $status = $newBalance < 0 ? 'Pending' : 'Settled';
                $actionType = 'Payment';

                $stmt = $conn->prepare("INSERT INTO credit_sale_data (bill_number, total_amount, received_amount, balance_amount, total_discount, status, customer_name, customer_contact, payable_amount, action_type, bill_date, bill_time, entered_date, entered_time, entered_user) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->bind_param(
                    "sddddsssdssssss",
                    $bill['bill_number'],
                    $bill['total_amount'],
                    $newReceived,
                    $newBalance,
                    $bill['total_discount'],
                    $status,
                    $customerName,
                    $customerContact,
                    $payable_amount,
                    $actionType,
                    $bill['entered_date'],
                    $bill['entered_time'],
                    $today,
                    $timeNow,
                    $loggedUser
                );
                $stmt->execute();
                $message = 'Credit payment saved successfully.';
            } else {
                $message = 'Bill not found.';
                $messageClass = 'error-box';
            }
        }
    }
}

$billSearch = trim($_GET['bill_number'] ?? '');
$historyCustomer = trim($_GET['history_customer'] ?? '');
$editCustomerId = (int)($_GET['edit_customer_id'] ?? 0);

$customers = $conn->query("SELECT * FROM credit_customer ORDER BY id DESC");
$editCustomer = null;
if ($editCustomerId > 0) {
    $editCustomer = getSelectedCustomer($conn, $editCustomerId);
}

$searchedBill = null;
$attachedCustomer = null;
if ($billSearch !== '') {
    $stmt = $conn->prepare("SELECT * FROM selling_data WHERE bill_number = ? LIMIT 1");
    $stmt->bind_param("s", $billSearch);
    $stmt->execute();
    $searchedBill = $stmt->get_result()->fetch_assoc();

    $stmt2 = $conn->prepare("SELECT customer_name, customer_contact FROM credit_sale_data WHERE bill_number = ? AND customer_name <> '' ORDER BY id DESC LIMIT 1");
    $stmt2->bind_param("s", $billSearch);
    $stmt2->execute();
    $attachedCustomer = $stmt2->get_result()->fetch_assoc();
}

$historyRows = null;
if ($historyCustomer !== '') {
    $stmt = $conn->prepare("
        SELECT *,
        CASE WHEN balance_amount < 0 AND DATEDIFF(CURDATE(), bill_date) > 7 THEN 0 ELSE 1 END AS pending_priority
        FROM credit_sale_data
        WHERE customer_name LIKE CONCAT('%', ?, '%')
        ORDER BY pending_priority ASC, bill_date ASC, id DESC
    ");
    $stmt->bind_param("s", $historyCustomer);
    $stmt->execute();
    $historyRows = $stmt->get_result();
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Credit Sale</title>
    <link rel="stylesheet" href="assets/style.css">
</head>
<body>
<div class="layout">
    <?php renderSidebar('credit_sale'); ?>
    <main class="main-content">
        <div class="topbar">Logged User: <?php echo $_SESSION['name']; ?> | <?php echo $_SESSION['user_category']; ?></div>

        <?php if ($message !== '') { ?>
            <div class="message-box <?php echo $messageClass; ?>"><?php echo htmlspecialchars($message); ?></div>
        <?php } ?>

        <div class="credit-layout">
            <div class="credit-card">
                <h2>Add Customer</h2>
                <form method="POST" class="credit-form-grid">
                    <input type="hidden" name="action" value="add_customer">
                    <input type="text" name="customer_name" placeholder="Customer Name" required>
                    <input type="text" name="customer_contact" placeholder="Contact" required>
                    <button type="submit">Submit</button>
                </form>
            </div>

            <div class="credit-card">
                <h2>Customer Management</h2>
                <form method="GET" class="credit-form-grid">
                    <select name="edit_customer_id">
                        <option value="">Select Customer</option>
                        <?php
                        $customerManageList = $conn->query("SELECT * FROM credit_customer ORDER BY customer_name ASC");
                        while ($cust = $customerManageList->fetch_assoc()) {
                            $selected = $editCustomerId === (int)$cust['id'] ? 'selected' : '';
                            echo '<option value="' . (int)$cust['id'] . '" ' . $selected . '>' . htmlspecialchars($cust['customer_name']) . ' - ' . htmlspecialchars($cust['customer_contact']) . '</option>';
                        }
                        ?>
                    </select>
                    <button type="submit">Load Customer</button>
                </form>

                <form method="POST" class="credit-form-grid" style="margin-top:15px;">
                    <input type="hidden" name="customer_id" value="<?php echo $editCustomer['id'] ?? 0; ?>">
                    <input type="text" name="customer_name" placeholder="Customer Name" value="<?php echo htmlspecialchars($editCustomer['customer_name'] ?? ''); ?>" required>
                    <input type="text" name="customer_contact" placeholder="Contact" value="<?php echo htmlspecialchars($editCustomer['customer_contact'] ?? ''); ?>" required>
                    <button type="submit" name="action" value="update_customer" class="action-btn">Update</button>
                    <button type="submit" name="action" value="delete_customer" class="action-btn delete-btn" onclick="return confirm('Are you sure you want to delete this customer?')">Delete</button>
                </form>
            </div>

            <div class="credit-card">
                <h2>Bill Number Search</h2>
                <form method="GET" class="credit-form-grid">
                    <input type="text" name="bill_number" placeholder="Enter Bill Number" value="<?php echo htmlspecialchars($billSearch); ?>">
                    <button type="submit">Search</button>
                </form>

                <?php if ($searchedBill) { ?>
                    <div class="credit-summary">
                        <div class="info-pill">Bill Number: <?php echo htmlspecialchars($searchedBill['bill_number']); ?></div>
                        <div class="info-pill">Total: Rs. <?php echo number_format($searchedBill['total_amount'], 2); ?></div>
                        <div class="info-pill">Received: Rs. <?php echo number_format($searchedBill['received_amount'], 2); ?></div>
                        <div class="info-pill">Balance: Rs. <?php echo number_format($searchedBill['balance_amount'], 2); ?></div>
                        <div class="info-pill">Date: <?php echo htmlspecialchars($searchedBill['entered_date']); ?></div>
                        <div class="info-pill">User: <?php echo htmlspecialchars($searchedBill['entered_user']); ?></div>
                    </div>

                    <div class="notice-box" style="margin-top:15px;">
                        Attached Customer:
                        <?php if ($attachedCustomer) { ?>
                            <?php echo htmlspecialchars($attachedCustomer['customer_name']); ?> | <?php echo htmlspecialchars($attachedCustomer['customer_contact']); ?>
                        <?php } else { ?>
                            Not attached yet.
                        <?php } ?>
                    </div>

                    <form method="POST" class="credit-form-grid" style="margin-top:15px;">
                        <input type="hidden" name="action" value="attach_customer">
                        <input type="hidden" name="bill_number" value="<?php echo htmlspecialchars($searchedBill['bill_number']); ?>">
                        <select name="selected_customer_id" required>
                            <option value="">Select Customer</option>
                            <?php
                            $customerList = $conn->query("SELECT * FROM credit_customer ORDER BY customer_name ASC");
                            while ($cust = $customerList->fetch_assoc()) {
                                echo '<option value="' . (int)$cust['id'] . '">' . htmlspecialchars($cust['customer_name']) . ' - ' . htmlspecialchars($cust['customer_contact']) . '</option>';
                            }
                            ?>
                        </select>
                        <button type="submit">Attach Customer</button>
                    </form>

                    <form method="POST" class="pay-section">
                        <input type="hidden" name="action" value="pay_credit">
                        <input type="hidden" name="bill_number" value="<?php echo htmlspecialchars($searchedBill['bill_number']); ?>">
                        <input type="number" step="0.01" min="0" name="credit_payable" placeholder="Credit Payable">
                        <button type="submit" class="pay-btn">Pay</button>
                    </form>
                <?php } elseif ($billSearch !== '') { ?>
                    <div class="message-box error-box">Bill not found.</div>
                <?php } ?>
            </div>

            <div class="credit-card">
                <h2>Customer Credit History</h2>
                <form method="GET" class="credit-form-grid">
                    <input type="text" name="history_customer" placeholder="Search Customer Name" value="<?php echo htmlspecialchars($historyCustomer); ?>">
                    <button type="submit">Search</button>
                </form>

                <?php if ($historyRows) { ?>
                    <div class="table-scroll">
                        <table>
                            <tr>
                                <th>Bill No</th>
                                <th>Customer</th>
                                <th>Contact</th>
                                <th>Action</th>
                                <th>Payable</th>
                                <th>Balance</th>
                                <th>Bill Date</th>
                                <th>Entered User</th>
                            </tr>
                            <?php while ($row = $historyRows->fetch_assoc()) {
                                $pendingLong = ((float)$row['balance_amount'] < 0) && ((strtotime(date('Y-m-d')) - strtotime($row['bill_date'])) > 7 * 24 * 60 * 60);
                            ?>
                                <tr class="<?php echo $pendingLong ? 'pending-credit' : ''; ?>">
                                    <td><?php echo htmlspecialchars($row['bill_number']); ?></td>
                                    <td><?php echo htmlspecialchars($row['customer_name']); ?></td>
                                    <td><?php echo htmlspecialchars($row['customer_contact']); ?></td>
                                    <td><?php echo htmlspecialchars($row['action_type']); ?></td>
                                    <td><?php echo number_format((float)$row['payable_amount'], 2); ?></td>
                                    <td><?php echo number_format((float)$row['balance_amount'], 2); ?></td>
                                    <td><?php echo htmlspecialchars($row['bill_date']); ?></td>
                                    <td><?php echo htmlspecialchars($row['entered_user']); ?></td>
                                </tr>
                            <?php } ?>
                        </table>
                    </div>
                <?php } ?>
            </div>
        </div>        </div>
    </main>
</div>
</body>
</html>