<?php
require 'db.php';
include 'layout.php';

// Step 1: Handle search/filter
$date = $_GET['date'] ?? date('Y-m-d');
$search = trim($_GET['search'] ?? '');
$sale_id = isset($_GET['sale_id']) ? intval($_GET['sale_id']) : 0;
$return_success = false;
$return_message = '';

// Step 2: Handle return submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['sale_id'])) {
    $sale_id = intval($_POST['sale_id']);
    $customer_remarks = trim($_POST['remarks'] ?? '');
    $return_qtys = $_POST['return_qty'] ?? [];
    $return_type = $_POST['return_type'] ?? 'whole';

    // Fetch sale and customer_id
    $sale = $conn->query("SELECT * FROM sales WHERE id = $sale_id")->fetch_assoc();
    if (!$sale) {
        $return_message = "<div class='alert alert-danger'>Sale not found.</div>";
    } else {
        $customer_id = 1; // Default Walk-in, or fetch from your sales table if you have customer_id
        $total_return = 0;
        // Insert with empty remarks (system reference will be set after insert)
        $conn->query("INSERT INTO sale_returns (sale_id, customer_id, total_amount, remarks, customer_remarks) VALUES ($sale_id, $customer_id, 0, '', '" . $conn->real_escape_string($customer_remarks) . "')");
        $sale_return_id = $conn->insert_id;

        // Insert items and inventory movements
        $items = $conn->query("SELECT * FROM sale_items WHERE sale_id = $sale_id");
        while ($item = $items->fetch_assoc()) {
            $item_id = $item['id'];
            $qty = isset($return_qtys[$item_id]) ? intval($return_qtys[$item_id]) : 0;
            if ($qty > 0 && $qty <= $item['quantity']) {
                $unit_price = $item['unit_price'];
                $total_price = $qty * $unit_price;
                $total_return += $total_price;
                $conn->query("INSERT INTO sale_return_items (sale_return_id, item_id, quantity, unit_price, total_price, tax_rate) VALUES ($sale_return_id, {$item['item_id']}, $qty, $unit_price, $total_price, {$item['tax_rate']})");
                // Add inventory movement (in)
                $conn->query("INSERT INTO inventory_movements (item_id, movement_type, reference_type, reference_id, quantity) VALUES ({$item['item_id']}, 'in', 'sale_return', $sale_return_id, $qty)");
            }
        }
        // Update total_amount in sale_returns
        $conn->query("UPDATE sale_returns SET total_amount = $total_return, remarks = 'Sale Return #$sale_return_id' WHERE id = $sale_return_id");
        $return_success = true;
        $return_message = "<div class='alert alert-success'>Sale return processed successfully!</div>";

        // --- FBR Integration for Sale Return ---
        // Fetch FBR config
        $fbr_config = [
            'enabled' => false,
            'api_url' => '',
            'pos_id' => '',
            'usin' => ''
        ];
        $result = $conn->query("SELECT * FROM fbr_config LIMIT 1");
        if ($result && $result->num_rows > 0) {
            $row = $result->fetch_assoc();
            $fbr_config = [
                'enabled' => $row['is_enabled'] == 1,
                'api_url' => $row['api_url'],
                'pos_id' => $row['pos_id'],
                'usin' => $row['usin']
            ];
        }
        if ($fbr_config['enabled']) {
            // Fetch original sale USIN
            $original_usin = $sale['invoice_number']; // or $sale['usin'] if you use a usin field
            // Prepare FBR items for return (only returned items)
            $items_for_fbr = [];
            $item_result = $conn->query("SELECT sri.item_id, si.item_name, sri.unit_price, sri.quantity, sri.tax_rate FROM sale_return_items sri JOIN sale_items si ON sri.item_id = si.id WHERE sri.sale_return_id = $sale_return_id");
            if ($item_result) {
                while ($row = $item_result->fetch_assoc()) {
                    $unit_price_inclusive = $row['unit_price'];
                    $qty = $row['quantity'];
                    $tax_rate = $row['tax_rate'];
                    $unit_price_exclusive = $unit_price_inclusive / (1 + ($tax_rate / 100));
                    $tax_per_unit = $unit_price_inclusive - $unit_price_exclusive;
                    $sale_value = $unit_price_exclusive * $qty;
                    $tax_charged = $tax_per_unit * $qty;
                    $total = $unit_price_inclusive * $qty;
                    $pct_code = '00000000'; // You can fetch from items table if needed
                    $items_for_fbr[] = [
                        "ItemCode"     => (string)$row['item_id'],
                        "ItemName"     => $row['item_name'],
                        "PCTCode"      => $pct_code,
                        "Quantity"     => (float)$qty,
                        "TaxRate"      => (float)$tax_rate,
                        "SaleValue"    => round($sale_value, 2),
                        "Discount"     => 0.00,
                        "FurtherTax"   => 0.00,
                        "TaxCharged"   => round($tax_charged, 2),
                        "TotalAmount"  => round($total, 2),
                        "InvoiceType"  => 2,
                        "RefUSIN"      => $original_usin
                    ];
                }
            }
            // Prepare FBR payload for return
            $fbr_data = [
                "InvoiceNumber"    => "",
                "POSID"            => $fbr_config['pos_id'],
                "USIN"             => "RET" . $sale_return_id,
                "DateTime"         => date('Y-m-d H:i:s'),
                "BuyerNTN"         => "",
                "BuyerCNIC"        => "",
                "BuyerName"        => $sale['customer_name'],
                "BuyerPhoneNumber" => "",
                "TotalBillAmount"  => $total_return,
                "TotalQuantity"    => array_sum(array_column($items_for_fbr, 'Quantity')),
                "TotalSaleValue"   => $total_return,
                "TotalTaxCharged"  => 0.00, // You can sum tax_charged if needed
                "Discount"         => 0.00,
                "FurtherTax"       => 0.00,
                "PaymentMode"      => 1,
                "RefUSIN"          => $original_usin,
                "InvoiceType"      => 2,
                "Items"            => $items_for_fbr
            ];
            $jsonData = json_encode($fbr_data);
            file_put_contents('fbr_last_payload_return.json', $jsonData);
            $ch = curl_init($fbr_config['api_url']);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Content-Type: application/json',
                'Content-Length: ' . strlen($jsonData)
            ]);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
            $response = curl_exec($ch);
            if (curl_errno($ch)) {
                error_log("Curl error: " . curl_error($ch));
            }
            curl_close($ch);
            file_put_contents('fbr_last_response_return.json', $response);
            $fbr_response = json_decode($response, true);
            // Log FBR response
            $stmt = $conn->prepare("INSERT INTO fbr_logs (sale_id, response) VALUES (?, ?)");
            $response_json = json_encode($fbr_response, JSON_UNESCAPED_UNICODE);
            $stmt->bind_param("is", $sale_return_id, $response_json);
            $stmt->execute();
            $stmt->close();
            // Save FBR invoice if available
            if (!empty($fbr_response['InvoiceNumber']) && $fbr_response['InvoiceNumber'] !== "Not Available") {
                $fbr_invoice = $fbr_response['InvoiceNumber'];
                $qr_data = $fbr_response['QRData'] ?? null;
                $stmt = $conn->prepare("INSERT INTO fbr_invoices (sale_id, fbr_invoice_number, qr_code) VALUES (?, ?, ?)");
                $stmt->bind_param("iss", $sale_return_id, $fbr_invoice, $qr_data);
                $stmt->execute();
                $stmt->close();
                $stmt = $conn->prepare("UPDATE sale_returns SET is_fbr_enabled = 1, fbr_invoice_number = ?, fbr_qr_data = ? WHERE id = ?");
                $stmt->bind_param("ssi", $fbr_invoice, $qr_data, $sale_return_id);
                $stmt->execute();
                $stmt->close();
            }
        }
        // --- END FBR Integration ---
    }
}
?>
<div class="page-wrapper">
  <div class="content">
    <h4>Sales Return</h4>
    <!-- Search/filter form -->
    <form method="get" class="row g-2 mb-3">
      <div class="col-md-3">
        <input type="date" name="date" value="<?= htmlspecialchars($date) ?>" class="form-control">
      </div>
      <div class="col-md-4">
        <input type="text" name="search" value="<?= htmlspecialchars($search) ?>" class="form-control" placeholder="Invoice # or Customer">
      </div>
      <div class="col-md-2">
        <button type="submit" class="btn btn-primary">Search</button>
      </div>
    </form>

    <?php if ($return_message) echo $return_message; ?>

    <?php
    // If no sale selected, show invoice list
    if (!$sale_id || $return_success) {
        $where = ["DATE(sale_date) = '" . $conn->real_escape_string($date) . "'"];
        if ($search !== '') {
            $search_sql = $conn->real_escape_string($search);
            $where[] = "(invoice_number LIKE '%$search_sql%' OR customer_name LIKE '%$search_sql%')";
        }
        $where_clause = count($where) ? 'WHERE ' . implode(' AND ', $where) : '';
        $sql = "SELECT id, invoice_number, sale_date, customer_name FROM sales $where_clause ORDER BY sale_date DESC LIMIT 50";
        $result = $conn->query($sql);
        ?>
        <table class="table table-bordered">
          <thead>
            <tr>
              <th>Invoice #</th>
              <th>Date</th>
              <th>Customer</th>
              <th>Action</th>
            </tr>
          </thead>
          <tbody>
            <?php while ($row = $result->fetch_assoc()): ?>
              <tr>
                <td><?= htmlspecialchars($row['invoice_number']) ?></td>
                <td><?= htmlspecialchars($row['sale_date']) ?></td>
                <td><?= htmlspecialchars($row['customer_name']) ?></td>
                <td>
                  <a href="?sale_id=<?= $row['id'] ?>&date=<?= urlencode($date) ?>&search=<?= urlencode($search) ?>" class="btn btn-warning btn-sm">Return</a>
                </td>
              </tr>
            <?php endwhile; ?>
          </tbody>
        </table>
        <?php
    } else {
        // Step 4: Show sale details and return form for selected invoice
        $sale = $conn->query("SELECT * FROM sales WHERE id = $sale_id")->fetch_assoc();
        $items = $conn->query("SELECT * FROM sale_items WHERE sale_id = $sale_id");
        ?>
        <h5>Return for Invoice: <?= htmlspecialchars($sale['invoice_number']) ?></h5>
        <form method="post" id="sale-return-form">
          <input type="hidden" name="sale_id" value="<?= $sale_id ?>">
          <div class="mb-3">
            <label class="form-label">Return Type:</label>
            <div>
              <input type="radio" name="return_type" value="whole" id="return_whole" checked>
              <label for="return_whole" style="margin-right: 20px;">Return Whole Bill</label>
              <input type="radio" name="return_type" value="itemwise" id="return_itemwise">
              <label for="return_itemwise">Return Item-wise</label>
            </div>
          </div>
          <table class="table table-bordered">
            <thead>
              <tr>
                <th>Item</th>
                <th>Sold Qty</th>
                <th>Return Qty</th>
                <th>Unit Price</th>
                <th>Total</th>
              </tr>
            </thead>
            <tbody>
              <?php while ($item = $items->fetch_assoc()): ?>
                <tr>
                  <td><?= htmlspecialchars($item['item_name']) ?></td>
                  <td><?= $item['quantity'] ?></td>
                  <td>
                    <input type="number" name="return_qty[<?= $item['id'] ?>]" min="0" max="<?= $item['quantity'] ?>" value="0" class="form-control return-qty-input" style="width:80px;">
                  </td>
                  <td><?= number_format($item['unit_price'], 2) ?></td>
                  <td><?= number_format($item['total_price'], 2) ?></td>
                </tr>
              <?php endwhile; ?>
            </tbody>
          </table>
          <div class="mb-3">
            <label>Customer Remarks (optional)</label>
            <input type="text" name="remarks" class="form-control">
          </div>
          <button type="submit" class="btn btn-warning">Process Return</button>
        </form>
        <script>
        document.addEventListener('DOMContentLoaded', function() {
          function setReturnType() {
            var isWhole = document.getElementById('return_whole').checked;
            document.querySelectorAll('.return-qty-input').forEach(function(input) {
              if (isWhole) {
                input.value = input.max;
                input.readOnly = true;
              } else {
                input.value = 0;
                input.readOnly = false;
              }
            });
          }
          document.getElementById('return_whole').addEventListener('change', setReturnType);
          document.getElementById('return_itemwise').addEventListener('change', setReturnType);
          setReturnType();
        });
        </script>
        <?php
    }
    ?>
  </div>
</div>