<?php
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

include 'auth.php';
include "db.php";

// --- UPDATED LOGIC TO SAVE RETURN AND UPDATE LEDGER ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $purchase_id = $_POST['purchase_id'];
    $supplier_id = $_POST['supplier_id'];
    $return_date = $_POST['return_date'];
    $grand_total = $_POST['grand_total'];

    // 1. Insert into purchase_returns
    $insert_return = "INSERT INTO purchase_returns (purchase_id, supplier_id, return_date, grand_total) VALUES (?, ?, ?, ?)";
    $stmt = $conn->prepare($insert_return);
    $stmt->bind_param("iisd", $purchase_id, $supplier_id, $return_date, $grand_total);
    $stmt->execute();
    $return_id = $stmt->insert_id;

    // 2. Insert items into purchase_return_items table
    foreach ($_POST['items'] as $item) {
        if ($item['return_qty'] > 0) {
            $sql = "INSERT INTO purchase_return_items (return_id, product_id, price, quantity) VALUES (?, ?, ?, ?)";
            $stmt_item = $conn->prepare($sql);
            $stmt_item->bind_param("iidd", $return_id, $item['product_id'], $item['price'], $item['return_qty']);
            $stmt_item->execute();
        }
    }

    // 3. ADDED: Insert into transactions table for Ledger Update
    $trans_sql = "INSERT INTO transactions (reference_id, reference_type, voucher_id, date, description, type, amount, amount_type) 
                  VALUES (?, 'SUPPLIER', ?, ?, ?, 'DEBIT', ?, 'CASH')";
    $stmt_trans = $conn->prepare($trans_sql);
    $description = "Purchase Return #PCH-" . str_pad($purchase_id, 4, '0', STR_PAD_LEFT);
    $stmt_trans->bind_param("iisds", $supplier_id, $purchase_id, $return_date, $description, $grand_total);
    $stmt_trans->execute();

    echo "<script>alert('Return Entry Saved & Ledger Updated!'); window.location='purchase_list.php';</script>";
    exit();
}
// --- END OF UPDATED LOGIC ---

$purchase_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!$purchase_id) {
    die("Invalid Purchase ID for Return Processing.");
}

/* 📊 1. FETCH MAIN PURCHASE DETAILS */
$query = "
    SELECT p.id, p.purchase_date, p.supplier_id, s.name as supplier_name 
    FROM purchases p
    LEFT JOIN suppliers s ON p.supplier_id = s.id
    WHERE p.id = ?
";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $purchase_id);
$stmt->execute();
$purchase = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$purchase) {
    die("Original Purchase Invoice Not Found inside System!");
}

/* 📦 2. FETCH PURCHASE ITEMS */
$items_query = "
    SELECT pi.product_id, pi.price, pi.quantity as purchased_qty, p.product_name
    FROM purchase_items pi
    LEFT JOIN products p ON pi.product_id = p.product_id
    WHERE pi.purchase_id = ?
";
$stmt_items = $conn->prepare($items_query);
$stmt_items->bind_param("i", $purchase_id);
$stmt_items->execute();
$items_result = $stmt_items->get_result();
$products = [];
while ($row = $items_result->fetch_assoc()) {
    $products[] = $row;
}
$stmt_items->close();
?>

<!DOCTYPE html>
<html>
<head>
<title>Process Purchase Return</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet">

<style>
body { background:#eef2f7; font-family:'Poppins',sans-serif; margin:0; padding:20px; color:#333; }
.wrapper { max-width:1000px; margin:20px auto; background:#fff; border-radius:14px; box-shadow:0 8px 25px rgba(0,0,0,0.05); padding:25px; }
.header { display:flex; align-items:center; gap:10px; color:#dc3545; border-bottom:2px solid #f4f5f7; padding-bottom:15px; margin-bottom:20px; }
.header h2 { margin:0; font-size:22px; font-weight:700; }
.meta-grid { display:grid; grid-template-columns: repeat(3, 1fr); gap:15px; background:#f8f9fa; padding:15px; border-radius:10px; margin-bottom:20px; }
.meta-item h4 { margin:0 0 5px 0; font-size:12px; color:#888; text-transform:uppercase; }
.meta-item p { margin:0; font-size:14px; font-weight:600; }
.input-field { width:100%; padding:8px; border:1px solid #ddd; border-radius:6px; font-family:inherit; font-size:14px; box-sizing:border-box; }
table { width:100%; border-collapse:collapse; margin-bottom:20px; }
th { background:#dc3545; color:#fff; padding:12px; font-size:13px; text-align:left; }
td { padding:12px; border-bottom:1px solid #eee; font-size:14px; }
.text-right { text-align:right; }
.editable-price { width:90px; text-align:center; }
.return-qty-input { width:70px; text-align:center; font-weight:600; }
.summary-box { display:flex; flex-direction:column; align-items:flex-end; gap:10px; margin-top:15px; background:#fff5f5; padding:15px; border-radius:10px; }
.total-refund-row { font-size:18px; font-weight:700; color:#dc3545; }
.actions { display:flex; justify-content:space-between; margin-top:20px; }
.btn { padding:10px 20px; border-radius:8px; border:none; font-weight:600; font-size:13px; cursor:pointer; text-decoration:none; transition:0.2s; }
.btn-cancel { background:#e5e7eb; color:#4b5563; }
.btn-save { background:#dc3545; color:#fff; }
.btn-save:hover { background:#bd2130; }

/* Mobile View Responsive CSS */
@media (max-width: 768px) {
    .meta-grid { grid-template-columns: 1fr; }
    table, thead, tbody, th, td, tr { display: block; }
    thead tr { display: none; }
    tr { margin-bottom: 15px; border: 1px solid #ddd; border-radius: 8px; padding: 10px; background: #fafafa; }
    td { border: none; padding: 5px; display: flex; justify-content: space-between; align-items: center; }
    td::before { content: attr(data-label); font-weight: 700; color: #555; }
    .editable-price, .return-qty-input { width: 100px !important; }
}
</style>
</head>
<body>

<div class="wrapper">
    <form action="" method="POST">
        <input type="hidden" name="purchase_id" value="<?= $purchase['id'] ?>">
        <input type="hidden" name="supplier_id" value="<?= $purchase['supplier_id'] ?>">

        <div class="header">
            <span style="font-size:24px;">🔄</span>
            <h2>Process Purchase Return</h2>
        </div>

        <div class="meta-grid">
            <div class="meta-item">
                <h4>Original Invoice</h4>
                <p>#PCH-00<?= $purchase['id'] ?></p>
            </div>
            <div class="meta-item">
                <h4>Supplier Name</h4>
                <p><?= htmlspecialchars($purchase['supplier_name']) ?></p>
            </div>
            <div class="meta-item">
                <h4>Return Date</h4>
                <input type="date" name="return_date" class="input-field" value="<?= date('Y-m-d') ?>" required>
            </div>
        </div>

        <table>
            <thead>
                <tr>
                    <th style="width: 40%;">Product Name</th>
                    <th style="width: 15%; text-align: center;">Price</th>
                    <th style="width: 15%; text-align: center;">Purchased</th>
                    <th style="width: 15%; text-align: center;">Return</th>
                    <th style="width: 15%; text-align: right;">Total</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($products as $index => $item): ?>
                <tr>
                    <td data-label="Product Name:">
                        <b><?= htmlspecialchars($item['product_name']) ?></b>
                        <input type="hidden" name="items[<?= $index ?>][product_id]" value="<?= $item['product_id'] ?>">
                    </td>
                    <td data-label="Price:" style="text-align: center;">
                        <input type="number" step="0.01" name="items[<?= $index ?>][price]" class="input-field editable-price" value="<?= $item['price'] ?>" oninput="calculateRow(this)">
                    </td>
                    <td data-label="Purchased Qty:" style="text-align: center; color: #555;">
                        <?= $item['purchased_qty'] ?>
                        <input type="hidden" class="max-qty" value="<?= $item['purchased_qty'] ?>">
                    </td>
                    <td data-label="Return Qty:" style="text-align: center;">
                        <input type="number" name="items[<?= $index ?>][return_qty]" class="input-field return-qty-input" value="0" min="0" max="<?= $item['purchased_qty'] ?>" oninput="calculateRow(this)">
                    </td>
                    <td data-label="Total Refund:" class="text-right amount-text row-total" style="font-weight: 600;">
                        0.00 PKR
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <div class="summary-box">
            <div class="total-refund-row">
                Total Return Amount: <span id="grand_total_display">0.00</span> PKR
                <input type="hidden" name="grand_total" id="grand_total_input" value="0">
            </div>
        </div>

        <div class="actions">
            <a href="purchase_list.php" class="btn btn-cancel">Cancel</a>
            <button type="submit" class="btn btn-save">Save Return Entry</button>
        </div>
    </form>
</div>

<script>
function calculateRow(element) {
    let tr = element.closest('tr');
    let price = parseFloat(tr.querySelector('.editable-price').value) || 0;
    let qty = parseInt(tr.querySelector('.return-qty-input').value) || 0;
    let maxQty = parseInt(tr.querySelector('.max-qty').value) || 0;

    if (qty > maxQty) {
        alert("Return Quantity cannot exceed Purchased Quantity (" + maxQty + ")");
        tr.querySelector('.return-qty-input').value = 0;
        qty = 0;
    }

    let total = price * qty;
    tr.querySelector('.row-total').innerText = total.toFixed(2) + " PKR";
    updateGrandTotal();
}

function updateGrandTotal() {
    let grandTotal = 0;
    document.querySelectorAll('.row-total').forEach(function(row) {
        let val = parseFloat(row.innerText.replace(" PKR", "")) || 0;
        grandTotal += val;
    });

    document.getElementById('grand_total_display').innerText = grandTotal.toFixed(2);
    document.getElementById('grand_total_input').value = grandTotal.toFixed(2);
}
</script>

</body>
</html>