<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';
requirePermission('return_management');

$pdo = getDB();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_return') {
    $sale_id = (int)$_POST['sale_id'];
    $customer_id = (int)$_POST['customer_id'];
    $return_type = $_POST['return_type'];
    $reason = trim($_POST['reason']);
    $refund_amount = (float)$_POST['refund_amount'];
    $product_id = (int)$_POST['product_id'];
    $imei_id = !empty($_POST['imei_id']) ? (int)$_POST['imei_id'] : null;

    try {
        $pdo->beginTransaction();
        $return_no = generateReturnNo();
        $stmt = $pdo->prepare("INSERT INTO returns_ (return_no, return_type, sales_invoice_id, customer_id, return_date, refund_amount, reason, status, created_by) VALUES (?,?,?,?,CURDATE(),?,'Pending','Pending',?)");
        $stmt->execute([$return_no, $return_type, $sale_id, $customer_id, $refund_amount, $_SESSION['user_id']]);
        $return_id = $pdo->lastInsertId();

        $stmt = $pdo->prepare("INSERT INTO return_items (return_id, product_id, imei_id, quantity, refund_amount) VALUES (?,?,?,1,?)");
        $stmt->execute([$return_id, $product_id, $imei_id, $refund_amount]);

        // Restore stock
        $pdo->prepare("UPDATE products SET current_stock = current_stock + 1 WHERE id = ?")->execute([$product_id]);

        if ($imei_id) {
            $pdo->prepare("UPDATE product_imei SET status = 'Returned' WHERE id = ?")->execute([$imei_id]);
        }

        $pdo->commit();
        logActivity('Created Return', 'Returns', $return_id);
        $_SESSION['success'] = "Return #$return_no processed.";
    } catch (Exception $e) { $pdo->rollBack(); $_SESSION['error'] = 'Error: ' . $e->getMessage(); }
    header('Location: returns.php'); exit;
}

$returns = $pdo->query("
    SELECT r.*, c.name as customer_name, c.phone as customer_phone, u.name as created_by_name
    FROM returns_ r
    LEFT JOIN customers c ON r.customer_id = c.id
    LEFT JOIN users u ON r.created_by = u.id
    ORDER BY r.id DESC
")->fetchAll();

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="content-wrapper">
    <div class="container-fluid">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h4 class="page-title mb-0"><i class="fas fa-undo me-2"></i>Returns & Exchanges</h4>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#returnModal"><i class="fas fa-plus me-1"></i>New Return</button>
        </div>
        <?php if (isset($_SESSION['success'])): ?><div class="alert alert-success alert-dismissible"><?= $_SESSION['success']; unset($_SESSION['success']); ?></div><?php endif; ?>
        <?php if (isset($_SESSION['error'])): ?><div class="alert alert-danger alert-dismissible"><?= $_SESSION['error']; unset($_SESSION['error']); ?></div><?php endif; ?>
        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table id="returnsTable" class="table table-hover datatable">
                        <thead><tr><th>Return #</th><th>Type</th><th>Customer</th><th>Date</th><th>Refund</th><th>Reason</th><th>Status</th><th>Created By</th></tr></thead>
                        <tbody>
                            <?php foreach ($returns as $r): ?>
                            <tr>
                                <td><strong><?= htmlspecialchars($r['return_no']) ?></strong></td>
                                <td><span class="badge bg-<?= $r['return_type'] == 'Sale Return' ? 'warning' : 'info' ?>"><?= $r['return_type'] ?></span></td>
                                <td><?= htmlspecialchars($r['customer_name'] ?? '-') ?></td>
                                <td><?= formatDate($r['return_date']) ?></td>
                                <td><?= formatCurrency($r['total_refund']) ?></td>
                                <td><?= htmlspecialchars($r['reason'] ?? '-') ?></td>
                                <td><?= getStatusBadge($r['status']) ?></td>
                                <td><?= htmlspecialchars($r['created_by_name'] ?? '-') ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="returnModal" tabindex="-1">
    <div class="modal-dialog">
        <form method="POST" class="modal-content">
            <input type="hidden" name="action" value="add_return">
            <div class="modal-header"><h5 class="modal-title">New Return</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">Return Type</label>
                    <select name="return_type" class="form-select">
                        <option value="Sale Return">Sale Return</option>
                        <option value="Exchange">Exchange</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">Customer *</label>
                    <select name="customer_id" class="form-select" required>
                        <option value="">Select</option>
                        <?php
                        $customers = $pdo->query("SELECT * FROM customers WHERE status=1 ORDER BY name")->fetchAll();
                        foreach ($customers as $c): ?>
                        <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['name']) ?> (<?= htmlspecialchars($c['phone']) ?>)</option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">Sale Invoice *</label>
                    <select name="sale_id" class="form-select" required>
                        <option value="">Select</option>
                        <?php
                        $invoices = $pdo->query("SELECT id, invoice_no FROM sales_invoices WHERE invoice_status != 'Cancelled' ORDER BY id DESC LIMIT 50")->fetchAll();
                        foreach ($invoices as $inv): ?>
                        <option value="<?= $inv['id'] ?>"><?= htmlspecialchars($inv['invoice_no']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">Product *</label>
                    <select name="product_id" class="form-select" required>
                        <option value="">Select</option>
                        <?php
                        $prods = $pdo->query("SELECT * FROM products WHERE status=1 ORDER BY product_name")->fetchAll();
                        foreach ($prods as $pr): ?>
                        <option value="<?= $pr['id'] ?>"><?= htmlspecialchars($pr['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">IMEI (for phones)</label>
                    <select name="imei_id" class="form-select">
                        <option value="">N/A</option>
                        <?php
                        $imeis = $pdo->query("SELECT pi.id, pi.imei_number, p.product_name as pname FROM product_imei pi JOIN products p ON pi.product_id = p.id WHERE pi.status = 'Sold' ORDER BY pi.id DESC LIMIT 50")->fetchAll();
                        foreach ($imeis as $im): ?>
                        <option value="<?= $im['id'] ?>"><?= htmlspecialchars($im['imei_number']) ?> (<?= htmlspecialchars($im['pname']) ?>)</option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">Refund Amount *</label>
                    <input type="number" step="0.01" name="refund_amount" class="form-control" required>
                </div>
                <div class="mb-3">
                    <label class="form-label">Reason</label>
                    <textarea name="reason" class="form-control" rows="2"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" class="btn btn-primary">Process Return</button>
            </div>
        </form>
    </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
