<?php
ob_start();

error_reporting(E_ALL);
ini_set('display_errors', 1);

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

// URL se Invoice ID uthana
$invoice_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!$invoice_id) {
    die("Invalid Invoice Reference for Return.");
}

/* 📊 1. FETCH ORIGINAL INVOICE & CUSTOMER INFO */
$query = "
    SELECT t.id as invoice_no, t.date, c.id as customer_id, c.name as customer_name
    FROM transactions t
    LEFT JOIN customers c ON t.reference_id = c.id
    WHERE t.id = ? AND t.reference_type = 'customer'
";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $invoice_id);
$stmt->execute();
$invoice = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$invoice) {
    die("Original Invoice Not Found!");
}

/* 📦 2. FETCH PRODUCTS IN THIS INVOICE FOR RETURN OPTIONS */
$items_query = "
    SELECT s.product_id, s.price, s.quantity as original_qty, p.product_name
    FROM sale_items s
    LEFT JOIN products p ON s.product_id = p.product_id
    WHERE s.transaction_id = ?
";
$stmt_items = $conn->prepare($items_query);
$stmt_items->bind_param("i", $invoice_id);
$stmt_items->execute();
$products_res = $stmt_items->get_result();
$invoice_products = [];
while($row = $products_res->fetch_assoc()) {
    $invoice_products[] = $row;
}
$stmt_items->close();


/* 💾 3. ACTION HANDLER: SAVE SALES RETURN */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $date = $_POST['return_date'];
    $return_products = $_POST['return_product_id'] ?? [];
    $return_qtys = $_POST['return_qty'] ?? [];
    $prices = $_POST['price'] ?? []; // Collected edited price array
    $other_charges = floatval($_POST['other_charges'] ?? 0);
    
    $return_subtotal = 0;
    $items_to_save = [];
    
    foreach ($return_products as $key => $p_id) {
        $r_qty = floatval($return_qtys[$key] ?? 0); // Kept floatval for point weight calculations
        $price = floatval($prices[$key] ?? 0);      // User's newly edited rate
        
        if ($r_qty > 0) {
            $item_total = $r_qty * $price;
            $return_subtotal += $item_total;
            
            $items_to_save[] = [
                'product_id' => intval($p_id),
                'quantity' => $r_qty,
                'price' => $price,
                'total' => $item_total
            ];
        }
    }
    
    // Final Grand Total includes items sum plus or minus custom other charges
    $final_return_grand = $return_subtotal + $other_charges;
    
    if ($final_return_grand > 0) {
        $customer_id = $invoice['customer_id'];
        $description = "Sales Return Against Invoice #INV-00" . $invoice['invoice_no'];
        $type = "Credit"; // Customer ledger mein return hamesha Credit entry banti hy
        $reference_type = "customer";
        
        // A. Transactions table mein return entry daalna
        $stmt_trans = $conn->prepare("INSERT INTO transactions (reference_id, reference_type, date, description, type, amount) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt_trans->bind_param("issssd", $customer_id, $reference_type, $date, $description, $type, $final_return_grand);
        
        if ($stmt_trans->execute()) {
            $return_trans_id = $stmt_trans->insert_id;
            
            // B. sale_return_items table mein items dump karna aur stock add-back karna
            $stmt_ret_item = $conn->prepare("INSERT INTO sale_return_items (transaction_id, product_id, quantity, price, total) VALUES (?, ?, ?, ?, ?)");
            foreach ($items_to_save as $item) {
                $stmt_ret_item->bind_param("iiidd", $return_trans_id, $item['product_id'], $item['quantity'], $item['price'], $item['total']);
                $stmt_ret_item->execute();
                
                // Optional: Agar return par stock automatically wapas warehouse me plus karna chahein
                $stockStmt = $conn->prepare("UPDATE products SET stock_quantity = stock_quantity + ? WHERE product_id = ?");
                $stockStmt->bind_param("di", $item['quantity'], $item['product_id']);
                $stockStmt->execute();
                $stockStmt->close();
            }
            $stmt_ret_item->close();
            
            header("Location: ledger_view.php?type=customer&id=" . $customer_id);
            exit();
        } else {
            echo "<script>alert('Error processing return: " . $conn->error . "');</script>";
        }
        $stmt_trans->close();
    } else {
        echo "<script>alert('Please enter return quantity or adjustments for calculation.');</script>";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Sales Return - INV-00<?= $invoice['invoice_no'] ?></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 {
    font-family: 'Poppins', sans-serif;
    background: #fdfefe;
    margin: 0;
    padding: 20px;
    color: #333;
}
.wrapper {
    max-width: 1100px;
    margin: 0 auto;
}
.card {
    background: #fff;
    padding: 10px;
}
.header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 25px;
}
.header h2 {
    margin: 0;
    color: #dc3545;
    font-size: 24px;
    font-weight: 700;
}
.icon-container {
    background: #007bff;
    color: #fff;
    width: 32px;
    height: 32px;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
}
.top-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20px;
    margin-bottom: 25px;
    background: #fff;
    padding: 20px;
    border: 1px solid #e5e7eb;
    border-radius: 8px;
}
.info-group label {
    font-size: 13px;
    font-weight: 500;
    color: #6b7280;
    display: block;
    margin-bottom: 6px;
}
.info-group p {
    margin: 0;
    font-size: 15px;
    font-weight: 600;
    color: #1f2937;
}
input[type="date"], input[type="number"] {
    padding: 8px 12px;
    border: 1px solid #d1d5db;
    border-radius: 6px;
    font-family: inherit;
    font-size: 14px;
    outline: none;
}
input[type="date"] { width: 100%; }

/* MOBILE RESPONSIVE WRAPPER */
.table-container {
    width: 100%;
    overflow-x: auto;
}

table {
    width: 100%;
    border-collapse: collapse;
    margin-bottom: 25px;
    min-width: 600px; /* Table ko mobile par chota hone se rokne ke liye */
}
thead {
    background: #dc3545;
    color: #fff;
}
th {
    padding: 12px 16px;
    text-align: left;
    font-size: 14px;
    font-weight: 600;
}
td {
    padding: 16px;
    border-bottom: 1px solid #f3f4f6;
    font-size: 14px;
    vertical-align: middle;
}
.td-center { text-align: center; }
.td-right { text-align: right; }

input[type="number"] {
    width: 100px;
    text-align: center;
}
input[type="number"]:focus {
    border-color: #dc3545;
}

/* ⭐ REALTIME EDITABLE PRICE FIELD */
.editable-price {
    width: 110px !important;
    text-align: left !important;
    font-weight: 500;
    background: #fff;
}

/* ⭐ OTHER CHARGES EXTRA ROW BOX CONTAINER */
.other-charges-box {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    gap: 12px;
    margin-bottom: 12px;
    padding-right: 15px;
    font-size: 14px;
    font-weight: 500;
    color: #4b5563;
}
.other-charges-box input {
    width: 130px;
    padding: 6px 10px;
    text-align: right;
    border: 1px solid #d1d5db;
    border-radius: 6px;
}

.grand-total-box {
    text-align: right;
    font-size: 16px;
    font-weight: 700;
    color: #dc3545;
    padding: 18px 24px;
    background: #fff5f5;
    border-radius: 8px;
    margin-bottom: 25px;
}
.btn-group {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.btn {
    padding: 10px 24px;
    border-radius: 6px;
    text-decoration: none;
    font-weight: 600;
    font-size: 14px;
    cursor: pointer;
    border: none;
    transition: 0.2s;
}
.btn-save { background: #dc3545; color: #fff; }
.btn-save:hover { background: #bd2130; }
.btn-cancel { background: #e5e7eb; color: #4b5563; }
.btn-cancel:hover { background: #d1d5db; }

/* MEDIA QUERY FOR MOBILE */
@media (max-width: 768px) {
    .top-grid {
        grid-template-columns: 1fr;
    }
}
</style>
</head>
<body>

<div class="wrapper">
<div class="card">
    <div class="header">
        <div class="icon-container"></div>
        <h2>Process Sales Return</h2>
    </div>

    <form method="POST" oninput="calculateReturnTotal()">
        <div class="top-grid">
            <div class="info-group">
                <label>Original Invoice</label>
                <p>#INV-00<?= $invoice['invoice_no'] ?></p>
            </div>
            <div class="info-group">
                <label>Customer Name</label>
                <p><b><?= htmlspecialchars($invoice['customer_name']) ?></b></p>
            </div>
            <div class="info-group">
                <label>Return Date</label>
                <input type="date" name="return_date" value="<?= date('Y-m-d') ?>" required>
            </div>
        </div>

        <div class="table-container">
            <table>
                <thead>
                    <tr>
                        <th style="width: 35%;">Product Name</th>
                        <th style="width: 20%;">Price (Editable)</th>
                        <th style="width: 15%;" class="td-center">Purchased Qty</th>
                        <th style="width: 15%;" class="td-center">Return Qty</th>
                        <th style="width: 15%;" class="td-right">Total Refund</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($invoice_products as $product){ ?>
                    <tr class="item-row">
                        <td>
                            <span style="font-weight: 600; color: #111827;"><?= htmlspecialchars($product['product_name']) ?></span>
                            <input type="hidden" name="return_product_id[]" value="<?= $product['product_id'] ?>">
                        </td>
                        <td>
                            <input type="number" step="0.01" class="row-price editable-price" name="price[]" value="<?= $product['price'] ?>" onkeyup="calculateReturnTotal()">
                        </td>
                        <td class="td-center"><span class="row-max-qty" style="font-weight: 500; color: #4b5563;"><?= $product['original_qty'] ?></span></td>
                        <td class="td-center">
                            <input type="number" step="0.01" name="return_qty[]" class="row-return-qty" value="0" min="0" max="<?= $product['original_qty'] ?>" onkeyup="validateQty(this)">
                        </td>
                        <td class="td-right" style="font-weight: 700; color: #111827;"><span class="row-total">0.00</span> PKR</td>
                    </tr>
                    <?php } ?>
                </tbody>
            </table>
        </div>

        <div class="other-charges-box">
            <label>Other Charges / Delivery Adjustments (+/-):</label>
            <input type="number" step="0.01" id="otherCharges" name="other_charges" value="0" onkeyup="calculateReturnTotal()">
        </div>

        <div class="grand-total-box">
            Total Return Amount: <span id="grandReturnTotal">0.00</span> PKR
        </div>

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

<script>
function validateQty(input) {
    let row = input.closest("tr");
    let maxQty = parseFloat(row.querySelector('.row-max-qty').innerText || 0);
    let currentVal = parseFloat(input.value || 0);
    
    if (currentVal > maxQty) {
        alert("Return quantity cannot be greater than purchased quantity (" + maxQty + ")");
        input.value = maxQty;
    }
    if (currentVal < 0) input.value = 0;
}

function calculateReturnTotal() {
    let itemsSubtotal = 0;
    
    document.querySelectorAll('.item-row').forEach(row => {
        let price = parseFloat(row.querySelector('.row-price').value || 0);
        let qty = parseFloat(row.querySelector('.row-return-qty').value || 0);
        
        let rowTotal = price * qty;
        row.querySelector('.row-total').innerText = rowTotal.toFixed(2);
        itemsSubtotal += rowTotal;
    });
    
    // Other dynamic configurations adder
    let otherCharges = parseFloat(document.getElementById('otherCharges').value || 0);
    let grandTotal = itemsSubtotal + otherCharges;
    
    document.getElementById('grandReturnTotal').innerText = grandTotal.toFixed(2);
}
</script>

</body>
</html>