<?php
require_once '../includes/auth.php';
require_once '../db.php';

requirePermission('master_sales', 'view', BASE_URL . '/dashboard.php');

require_once '../includes/header.php';
require_once '../includes/sidebar.php';

// ── Existing master returns (sales_returns linked to master invoices) ──
$returns = $conn->query("
    SELECT sr.id, sr.return_no, sr.return_date, sr.status, sr.total_amount,
           sr.sales_invoice_id,
           si.invoice_no, si.master_invoice_id,
           mi.master_no,
           c.name AS client_name,
           cm.company_name
    FROM sales_returns sr
    JOIN sales_invoices si ON si.id = sr.sales_invoice_id
    JOIN master_invoices mi ON mi.id = si.master_invoice_id
    JOIN clients c ON c.id = sr.client_id
    JOIN company_master cm ON cm.id = sr.company_id
    WHERE si.master_invoice_id IS NOT NULL
    ORDER BY sr.return_date DESC, sr.id DESC
");

// ── Master invoice search for creating new return ──
$search  = trim($_GET['search'] ?? '');
$searchResults = null;
if ($search !== '') {
    $s = $conn->real_escape_string($search);
    $searchResults = $conn->query("
        SELECT mi.id, mi.master_no, mi.invoice_date, mi.status,
               c.name AS client_name
        FROM master_invoices mi
        JOIN clients c ON c.id = mi.client_id
        WHERE mi.status = 'final'
          AND (mi.master_no LIKE '%$s%' OR c.name LIKE '%$s%')
        ORDER BY mi.invoice_date DESC
        LIMIT 20
    ");
}
?>

<div class="page-header">
    <h2><i class="fas fa-rotate-left" style="color:var(--primary);margin-right:8px;"></i>Master Sales Returns</h2>
    <button type="button" class="btn btn-primary" onclick="var p=document.getElementById('createPanel');p.style.display=p.style.display==='none'?'block':'none';if(p.style.display==='block'){p.querySelector('input[type=text]').focus();}"><i class="fas fa-plus" style="margin-right:6px;"></i>New Master Return</button>
</div>

<!-- ── Create New Return ── -->
<div id="createPanel" class="panel" style="margin-bottom:20px;display:<?= $search !== '' ? 'block' : 'none' ?>;">
    <div class="panel-header">
        <span class="panel-title"><i class="fas fa-plus-circle" style="margin-right:6px;"></i>Create New Return</span>
    </div>
    <div class="panel-body">
        <form method="get" style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
            <input type="text" name="search" placeholder="Search master invoice no. or client name..."
                   value="<?= htmlspecialchars($search) ?>"
                   style="font-size:13px;padding:7px 12px;border:1px solid var(--border);border-radius:6px;width:300px;">
            <button type="submit" class="btn btn-primary btn-sm"><i class="fas fa-search"></i> Search</button>
            <?php if ($search): ?>
            <a href="index.php" class="btn btn-secondary btn-sm">Clear</a>
            <?php endif; ?>
        </form>

        <?php if ($search !== '' && $searchResults !== null): ?>
        <div style="margin-top:14px;overflow-x:auto;">
            <?php if ($searchResults->num_rows > 0): ?>
            <table>
                <thead>
                    <tr>
                        <th>Master Ref</th>
                        <th>Date</th>
                        <th>Client</th>
                        <th style="text-align:center;">Action</th>
                    </tr>
                </thead>
                <tbody>
                <?php while ($row = $searchResults->fetch_assoc()): ?>
                <tr>
                    <td><strong><?= htmlspecialchars($row['master_no']) ?></strong></td>
                    <td><?= date('d-m-Y', strtotime($row['invoice_date'])) ?></td>
                    <td><?= htmlspecialchars($row['client_name']) ?></td>
                    <td style="text-align:center;">
                        <a href="create_master.php?master_id=<?= $row['id'] ?>" class="btn btn-sm btn-primary">
                            <i class="fas fa-rotate-left"></i> Create Return
                        </a>
                    </td>
                </tr>
                <?php endwhile; ?>
                </tbody>
            </table>
            <?php else: ?>
            <p style="color:var(--text-muted);padding:12px 0;">No finalized master invoices found for "<?= htmlspecialchars($search) ?>".</p>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- ── Existing Master Returns ── -->
<div class="panel">
    <div class="panel-header">
        <span class="panel-title">Master Returns List</span>
    </div>
    <div style="overflow-x:auto;">
        <table>
            <thead>
                <tr>
                    <th>Credit Note No</th>
                    <th>Return Date</th>
                    <th>Master Ref</th>
                    <th>Company</th>
                    <th>Client</th>
                    <th style="text-align:right;">Amount</th>
                    <th style="text-align:center;">Status</th>
                    <th style="text-align:center;">Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php if ($returns->num_rows > 0): while ($row = $returns->fetch_assoc()): ?>
            <tr>
                <td><strong><?= htmlspecialchars($row['return_no']) ?></strong></td>
                <td><?= date('d-m-Y', strtotime($row['return_date'])) ?></td>
                <td>
                    <a href="../master_sales/view.php?id=<?= $row['master_invoice_id'] ?>"
                       style="color:var(--primary);font-weight:600;">
                        <?= htmlspecialchars($row['master_no']) ?>
                    </a>
                </td>
                <td><span class="badge badge-gray" style="font-size:11px;"><?= htmlspecialchars($row['company_name']) ?></span></td>
                <td><?= htmlspecialchars($row['client_name']) ?></td>
                <td style="text-align:right;">&#8377; <?= number_format($row['total_amount'], 2) ?></td>
                <td style="text-align:center;">
                    <?php $s = $row['status']; ?>
                    <span class="badge <?= $s === 'final' ? 'badge-success' : 'badge-warning' ?>"><?= ucfirst($s) ?></span>
                </td>
                <td style="text-align:center;">
                    <div style="display:flex;gap:4px;justify-content:center;flex-wrap:wrap;">
                        <a href="view.php?id=<?= $row['id'] ?>" class="btn btn-sm btn-outline" title="View">
                            <i class="fas fa-eye"></i>
                        </a>
                        <?php if ($row['status'] === 'draft'): ?>
                        <a href="edit.php?id=<?= $row['id'] ?>" class="btn btn-sm btn-primary" title="Edit">
                            <i class="fas fa-edit"></i>
                        </a>
                        <?php endif; ?>
                        <a href="../sales_return/layout_loader_thermal.php?id=<?= $row['id'] ?>"
                           onclick="window.open(this.href,'thermal_<?= $row['id'] ?>','width=560,height=780,scrollbars=yes');return false;"
                           class="btn btn-sm btn-secondary" title="Print Thermal">
                            <i class="fas fa-receipt"></i>
                        </a>
                        <?php if ($row['status'] === 'draft'): ?>
                        <a href="delete.php?id=<?= $row['id'] ?>"
                           onclick="return confirm('Delete this draft credit note?')"
                           class="btn btn-sm btn-danger" title="Delete">
                            <i class="fas fa-trash"></i>
                        </a>
                        <?php endif; ?>
                    </div>
                </td>
            </tr>
            <?php endwhile; else: ?>
            <tr><td colspan="8" style="text-align:center;padding:32px;color:var(--text-muted);">No master returns found.</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php require_once '../includes/footer.php'; ?>
