<?php
include 'auth_check.php';

$search_bill_number = isset($_GET['bill_number']) ? trim($_GET['bill_number']) : '';
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['return_item'])) {
    $bill_number = trim($_POST['bill_number']);
    $product_name = trim($_POST['product_name']);
    $unit = trim($_POST['unit']);
    $selling_price = (float)$_POST['selling_price'];
    $qty = (float)$_POST['qty'];
    $discount = (float)$_POST['discount'];
    $line_total = (float)$_POST['line_total'];
    $entered_date = trim($_POST['entered_date']);
    $entered_time = trim($_POST['entered_time']);
    $entered_user = trim($_POST['entered_user']);
    $returned_user = $_SESSION['name'];
    $returned_datetime = date('Y-m-d H:i:s');
    $returned_date = date('Y-m-d');
    $returned_time = date('H:i:s');

    $checkReturned = $conn->prepare("SELECT status FROM billing_data WHERE bill_number=? AND product_name=? LIMIT 1");
    $checkReturned->bind_param("ss", $bill_number, $product_name);
    $checkReturned->execute();
    $checkReturnedResult = $checkReturned->get_result();
    $alreadyReturned = false;
    if ($checkReturnedResult->num_rows > 0) {
        $statusRow = $checkReturnedResult->fetch_assoc();
        if (isset($statusRow['status']) && $statusRow['status'] === 'Returned') {
            $alreadyReturned = true;
        }
    }

    if ($alreadyReturned) {
        $message = 'This item has already been returned.';
        $message_type = 'error-box';
    } else {
        $stockUp = $conn->prepare("UPDATE stock SET purchased_qty = purchased_qty + ? WHERE product_name = ?");
        $stockUp->bind_param("ds", $qty, $product_name);
        $stockUp->execute();

        $ret1 = $conn->prepare("INSERT INTO returned_product_data (bill_number, product_name, unit, selling_price, qty, discount, line_total, entered_date, entered_time, entered_user, returned_date, returned_time, returned_datetime, returned_user) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
        $ret1->bind_param(
            "sssdddssssssss",
            $bill_number,
            $product_name,
            $unit,
            $selling_price,
            $qty,
            $discount,
            $line_total,
            $entered_date,
            $entered_time,
            $entered_user,
            $returned_date,
            $returned_time,
            $returned_datetime,
            $returned_user
        );
        $ret1->execute();

        $ret2 = $conn->prepare("INSERT INTO bill_return (bill_number, product_name, unit, selling_price, returned_qty, discount, line_total, original_entered_date, original_entered_time, original_entered_user, returned_date, returned_time, returned_datetime, returned_user) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
        $ret2->bind_param(
            "sssdddssssssss",
            $bill_number,
            $product_name,
            $unit,
            $selling_price,
            $qty,
            $discount,
            $line_total,
            $entered_date,
            $entered_time,
            $entered_user,
            $returned_date,
            $returned_time,
            $returned_datetime,
            $returned_user
        );
        $ret2->execute();

        $upBilling = $conn->prepare("UPDATE billing_data SET status='Returned', returned_datetime=?, returned_user=? WHERE bill_number=? AND product_name=?");
        $upBilling->bind_param("ssss", $returned_datetime, $returned_user, $bill_number, $product_name);
        $upBilling->execute();

        $upSelling = $conn->prepare("UPDATE selling_data SET status='Returned', returned_datetime=?, returned_user=? WHERE bill_number=?");
        $upSelling->bind_param("sss", $returned_datetime, $returned_user, $bill_number);
        $upSelling->execute();

        $message = 'Bill item returned successfully.';
        $message_type = 'success-box';
        $search_bill_number = $bill_number;
    }
}

$billItems = null;
$billSummary = null;
if ($search_bill_number !== '') {
    $safeBillNo = $conn->real_escape_string($search_bill_number);
    $billItems = $conn->query("SELECT * FROM billing_data WHERE bill_number='$safeBillNo' ORDER BY id ASC");
    $billSummary = $conn->query("SELECT * FROM selling_data WHERE bill_number='$safeBillNo' LIMIT 1")->fetch_assoc();
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Krushi Sewa Piyasa-Bill Return</title>
    <link rel="stylesheet" href="assets/style.css">
</head>
<body>
<div class="layout">
    <?php renderSidebar('bill_return'); ?>
    <main class="main-content">
        <div class="topbar">Logged User: <?php echo $_SESSION['name']; ?> | <?php echo $_SESSION['user_category']; ?></div>

        <div class="table-card">
            <h2>Bill Return</h2>

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

            <form method="GET" class="search-bar">
                <input type="text" name="bill_number" placeholder="Enter Bill Number" value="<?php echo htmlspecialchars($search_bill_number); ?>" required>
                <button type="submit">Search</button>
            </form>
        </div>

        <?php if ($search_bill_number !== '') { ?>
            <div class="table-card">
                <h2>Bill Summary</h2>
                <?php if ($billSummary) { ?>
                    <div class="bill-return-summary">
                        <div><strong>Bill No:</strong> <?php echo htmlspecialchars($billSummary['bill_number']); ?></div>
                        <div><strong>Date:</strong> <?php echo htmlspecialchars($billSummary['entered_date'] . ' ' . $billSummary['entered_time']); ?></div>
                        <div><strong>User:</strong> <?php echo htmlspecialchars($billSummary['entered_user']); ?></div>
                        <div><strong>Total:</strong> Rs. <?php echo number_format((float)$billSummary['total_amount'], 2); ?></div>
                        <div><strong>Received:</strong> Rs. <?php echo number_format((float)$billSummary['received_amount'], 2); ?></div>
                        <div><strong>Balance:</strong> Rs. <?php echo number_format((float)$billSummary['balance_amount'], 2); ?></div>
                        <div><strong>Status:</strong> <?php echo !empty($billSummary['status']) ? htmlspecialchars($billSummary['status']) : 'Active'; ?></div>
                    </div>
                <?php } else { ?>
                    <div class="notice-box">No bill summary found for this bill number.</div>
                <?php } ?>
            </div>

            <div class="table-card">
                <h2>Bill Items</h2>
                <div class="table-scroll">
                    <table>
                        <tr>
                            <th>Bill No</th>
                            <th>Product</th>
                            <th>Unit</th>
                            <th>Unit Price</th>
                            <th>Qty</th>
                            <th>Discount</th>
                            <th>Total</th>
                            <th>Status</th>
                            <th>Returned At</th>
                            <th>Returned User</th>
                            <th>Action</th>
                        </tr>
                        <?php if ($billItems && $billItems->num_rows > 0) { ?>
                            <?php while($row = $billItems->fetch_assoc()) { ?>
                                <tr class="<?php echo (isset($row['status']) && $row['status'] === 'Returned') ? 'returned-row' : ''; ?>">
                                    <td><?php echo htmlspecialchars($row['bill_number']); ?></td>
                                    <td><?php echo htmlspecialchars($row['product_name']); ?></td>
                                    <td><?php echo htmlspecialchars($row['unit']); ?></td>
                                    <td><?php echo number_format((float)$row['selling_price'], 2); ?></td>
                                    <td><?php echo $row['qty']; ?></td>
                                    <td><?php echo number_format((float)$row['discount'], 2); ?></td>
                                    <td><?php echo number_format((float)$row['line_total'], 2); ?></td>
                                    <td><?php echo !empty($row['status']) ? htmlspecialchars($row['status']) : 'Active'; ?></td>
                                    <td><?php echo !empty($row['returned_datetime']) ? htmlspecialchars($row['returned_datetime']) : '-'; ?></td>
                                    <td><?php echo !empty($row['returned_user']) ? htmlspecialchars($row['returned_user']) : '-'; ?></td>
                                    <td>
                                        <?php if (isset($row['status']) && $row['status'] === 'Returned') { ?>
                                            <span class="returned-label">Returned</span>
                                        <?php } else { ?>
                                            <form method="POST" onsubmit="return confirm('Are you sure you want to return this item?');">
                                                <input type="hidden" name="return_item" value="1">
                                                <input type="hidden" name="bill_number" value="<?php echo htmlspecialchars($row['bill_number']); ?>">
                                                <input type="hidden" name="product_name" value="<?php echo htmlspecialchars($row['product_name']); ?>">
                                                <input type="hidden" name="unit" value="<?php echo htmlspecialchars($row['unit']); ?>">
                                                <input type="hidden" name="selling_price" value="<?php echo htmlspecialchars($row['selling_price']); ?>">
                                                <input type="hidden" name="qty" value="<?php echo htmlspecialchars($row['qty']); ?>">
                                                <input type="hidden" name="discount" value="<?php echo htmlspecialchars($row['discount']); ?>">
                                                <input type="hidden" name="line_total" value="<?php echo htmlspecialchars($row['line_total']); ?>">
                                                <input type="hidden" name="entered_date" value="<?php echo htmlspecialchars($row['entered_date']); ?>">
                                                <input type="hidden" name="entered_time" value="<?php echo htmlspecialchars($row['entered_time']); ?>">
                                                <input type="hidden" name="entered_user" value="<?php echo htmlspecialchars($row['entered_user']); ?>">
                                                <button type="submit" class="return-btn">Return</button>
                                            </form>
                                        <?php } ?>
                                    </td>
                                </tr>
                            <?php } ?>
                        <?php } else { ?>
                            <tr><td colspan="11">No bill items found for this bill number.</td></tr>
                        <?php } ?>
                    </table>
                </div>
            </div>
        <?php } ?>
    </main>
</div>
</body>
</html>
