<?php
session_start();
require_once("../config/config.php");

// Allowed roles
$allowed_roles = ['store manager', 'admin', 'project manager'];
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], $allowed_roles)) {
    header("Location: ../login.php");
    exit();
}
$project_id=$_GET['project_id'] ?? '';
// Handle Delete
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    mysqli_begin_transaction($conn);
    try {
        $conn->query("DELETE FROM supply_return_note_items WHERE srn_id = $id");
        $conn->query("DELETE FROM supply_return_note WHERE id = $id");
        
        mysqli_commit($conn);
        $success = "Supply Return Note deleted successfully!";
    } catch (Exception $e) {
        mysqli_rollback($conn);
        $error = "Error deleting SRN: " . $e->getMessage();
    }
}

// Fetch all SRNs with summary
$query = "
    SELECT 
        srn.id,
        srn.srn_code,
        srn.srn_date,
        srn.receiver_name,
        srn.status,
        srn.grand_total,
        srn.created_at,
        p.project_code,
        p.project_name,
        u.full_name AS created_by_name,
        COUNT(sri.id) AS item_count
    FROM supply_return_note srn
    LEFT JOIN project_master p ON srn.project_id = p.id
    LEFT JOIN users u ON srn.created_by = u.id
    LEFT JOIN supply_return_note_items sri ON srn.id = sri.srn_id
    GROUP BY srn.id
    ORDER BY srn.srn_date DESC, srn.id DESC
";
$result = $conn->query($query);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Supply Return Notes (SRN) List</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        :root {
            --primary: #a855f7;
            --glass: rgba(255,255,255,0.09);
            --border: rgba(255,255,255,0.18);
        }
        body {
            font-family: 'Inter', system-ui, sans-serif;
            background: linear-gradient(rgba(0,0,0,0.85), rgba(0,0,0,0.95)), url('../background.jpeg') center/cover fixed;
            color: #f1f5f9;
            margin: 0;
            padding: 20px;
        }
        .container { max-width: 1350px; margin: 0 auto; }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            flex-wrap: wrap;
            gap: 15px;
        }

        .add-btn {
            background: linear-gradient(135deg, var(--primary), #c084fc);
            color: white;
            padding: 14px 28px;
            border: none;
            border-radius: 14px;
            font-weight: 600;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 10px;
        }

        .glass-card {
            background: var(--glass);
            backdrop-filter: blur(20px);
            border: 1px solid var(--border);
            border-radius: 24px;
            padding: 30px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.6);
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            padding: 16px 14px;
            text-align: left;
            border-bottom: 1px solid var(--border);
        }
        th {
            background: rgba(168,85,247,0.25);
            font-weight: 600;
        }
        tr:hover {
            background: rgba(255,255,255,0.08);
        }

        .status-badge {
            padding: 6px 14px;
            border-radius: 30px;
            font-size: 0.9rem;
            font-weight: 600;
        }
        .status-Pending { background: #eab308; color: black; }
        .status-Received { background: #22c55e; color: white; }
        .status-Rejected { background: #ef4444; color: white; }

        .action-btn {
            padding: 8px 16px;
            border-radius: 8px;
            text-decoration: none;
            margin-right: 6px;
            font-size: 0.95rem;
        }
        .btn-view { background: #3b82f6; color: white; }
        .btn-edit { background: #eab308; color: black; }
        .btn-delete { background: #ef4444; color: white; }

        .message {
            padding: 16px 24px;
            border-radius: 16px;
            margin-bottom: 25px;
            font-weight: 600;
        }
        .success { background: rgba(34,197,94,0.25); border: 1px solid #4ade80; color: #86efac; }
        .error   { background: rgba(239,68,68,0.25); border: 1px solid #f87171; color: #fca5a5; }
    </style>
</head>
<body>
<?php include '../config/header.php'; ?>
<div class="container">

    <div class="header">
        <h1><i class="fas fa-undo"></i> Supply Return Notes (SRN)</h1>
        <a href="add_srn.php?project_id=<?= $project_id ?>" class="add-btn">
            <i class="fas fa-plus"></i> New Supply Return Note
        </a>
    </div>

    <?php if (isset($success)): ?>
        <div class="message success"><?= $success ?></div>
    <?php endif; ?>
    <?php if (isset($error)): ?>
        <div class="message error"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <div class="glass-card">
        <table>
            <thead>
                <tr>
                    <th>SRN Code</th>
                    <th>Date</th>
                    <th>Project</th>
                    <th>Receiver</th>
                    <th>Items</th>
                    <th>Grand Total</th>
                    <th>Status</th>
                    <th>Created By</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($result && $result->num_rows > 0): ?>
                    <?php while ($row = $result->fetch_assoc()): ?>
                    <tr>
                        <td><strong><?= htmlspecialchars($row['srn_code']) ?></strong></td>
                        <td><?= date('d M Y', strtotime($row['srn_date'])) ?></td>
                        <td><?= htmlspecialchars($row['project_name'] ?? '—') ?> 
                            <small>(<?= htmlspecialchars($row['project_code'] ?? '') ?>)</small></td>
                        <td><?= htmlspecialchars($row['receiver_name']) ?></td>
                        <td><?= $row['item_count'] ?> items</td>
                        <td><strong>₹ <?= number_format($row['grand_total'], 2) ?></strong></td>
                        <td>
                            <span class="status-badge status-<?= htmlspecialchars($row['status']) ?>">
                                <?= htmlspecialchars($row['status']) ?>
                            </span>
                        </td>
                        <td><?= htmlspecialchars($row['created_by_name'] ?? 'System') ?></td>
                        <td>
                            <a href="srn_view.php?id=<?= $row['id'] ?>" class="action-btn btn-view" title="View">
                                <i class="fas fa-eye"></i>
                            </a>
                            <?php if ($row['status'] === 'Pending'): ?>
                            <a href="srn_edit.php?id=<?= $row['id'] ?>" class="action-btn btn-edit" title="Edit">
                                <i class="fas fa-edit"></i>
                            </a>
                            <?php endif; ?>
                            <a href="srn_list.php?delete=<?= $row['id'] ?>" 
                               class="action-btn btn-delete" 
                               title="Delete"
                               onclick="return confirm('Are you sure you want to delete this SRN? This action cannot be undone.')">
                                <i class="fas fa-trash"></i>
                            </a>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="9" style="text-align:center; padding:80px; color:#94a3b8;">
                            <i class="fas fa-undo" style="font-size:48px; margin-bottom:15px; opacity:0.5;"></i><br>
                            No Supply Return Notes found.<br>
                            <a href="add_srn.php" style="color:var(--primary);">Create your first SRN →</a>
                        </td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

</div>

</body>
</html>

<?php $conn->close(); ?>