<?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();
}

$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role'];
$full_name = $_SESSION['full_name'] ?? 'User';

// Optional project filter
$project_id = isset($_GET['project_id']) ? (int)$_GET['project_id'] : 0;

// Build WHERE clause
$where = "";
$params = [];
$types = "";

if ($project_id > 0) {
    $where = " WHERE rc.project_id = ?";
    $params[] = $project_id;
    $types .= "i";
}

// Fetch Return Challan List
$query = "
    SELECT 
        rc.id,
        rc.rc_code,
        rc.rc_date,
        rc.sender_name,
        rc.receiver_name,
        rc.vehicle_no,
        rc.status,
        p.project_code,
        p.project_name,
        COUNT(rci.id) AS item_count,
        COALESCE(SUM(rci.returned_qty * COALESCE(rci.rate, 0)), 0) AS total_value,
        COALESCE(SUM(rci.returned_qty), 0) AS total_qty
    FROM return_challan rc
    LEFT JOIN project_master p ON rc.project_id = p.id
    LEFT JOIN return_challan_items rci ON rc.id = rci.rc_id
    $where
    GROUP BY rc.id
    ORDER BY rc.rc_date DESC, rc.id DESC
    LIMIT 100
";

$stmt = $conn->prepare($query);
if ($types) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Return Challan 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;
            --success: #22c55e;
            --warning: #f59e0b;
            --danger: #ef4444;
            --glass: rgba(255,255,255,0.08);
            --border: rgba(255,255,255,0.16);
        }
        body {
            font-family: 'Segoe UI', system-ui, sans-serif;
            background: linear-gradient(rgba(0,0,0,0.8), rgba(0,0,0,0.95)),
                        url('../background.jpeg') center/cover fixed;
            color: white;
            margin: 0;
            padding: 20px 15px;
        }
        .container { max-width: 1480px; margin: 0 auto; }

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

        .back {
            color: #c4b5fd;
            text-decoration: none;
            font-weight: 500;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        .back:hover { color: white; }

        .add-btn {
            background: linear-gradient(135deg, var(--primary), #c084fc);
            color: white;
            padding: 13px 26px;
            border: none;
            border-radius: 12px;
            font-size: 1.05rem;
            font-weight: 600;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 10px;
            box-shadow: 0 8px 20px rgba(168, 85, 247, 0.4);
        }
        .add-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 12px 28px rgba(168,85,247,0.5);
        }

        h1 { margin: 0 0 8px; font-size: 2.2rem; }
        .subtitle { opacity: 0.85; font-size: 1.1rem; margin-bottom: 20px; }

        .table-container {
            background: var(--glass);
            backdrop-filter: blur(14px);
            border: 1px solid var(--border);
            border-radius: 16px;
            overflow: hidden;
            box-shadow: 0 12px 35px rgba(0,0,0,0.45);
        }
        table { width: 100%; border-collapse: collapse; }
        th, td { padding: 15px 18px; text-align: left; }
        th { 
            background: rgba(255,255,255,0.13); 
            font-weight: 600;
            position: sticky;
            top: 0;
            z-index: 10;
        }
        tr { border-bottom: 1px solid var(--border); }
        tr:hover { background: rgba(255,255,255,0.06); }

        .status-badge {
            padding: 7px 14px;
            border-radius: 9999px;
            font-size: 0.87rem;
            font-weight: 600;
        }
        .status-Pending   { background: rgba(245,158,11,0.25); color: #fcd34d; }
        .status-Received  { background: rgba(34,197,94,0.25); color: #86efac; }
        .status-Completed { background: rgba(34,197,94,0.25); color: #86efac; }
        .status-Cancelled { background: rgba(239,68,68,0.25); color: #fca5a5; }

        .no-records {
            text-align: center;
            padding: 90px 30px;
            opacity: 0.85;
        }
        .no-records i { font-size: 4.5rem; margin-bottom: 20px; color: #64748b; }

        .action-link {
            color: var(--primary);
            margin-right: 14px;
            text-decoration: none;
        }
        .action-link:hover { color: #c4b5fd; }
    </style>
</head>
<body>
<?php include '../config/header.php' ?>
<div class="container">

    <div class="header-actions">
        <a href="../project/project_dashboard.php?id=<?= $project_id ?>" class="back">
            <i class="fas fa-arrow-left"></i> Back to Store Dashboard
        </a>
        
        <a href="add-project-dc.php?project_id=<?= $project_id ?>" class="add-btn">
            <i class="fas fa-plus"></i> Create New Return Challan
        </a>
    </div>

    <h1>Return Challans (Project → Warehouse)</h1>
    <div class="subtitle">
        <?= $project_id > 0 ? "Filtered by Project" : "All Projects" ?> 
        • <?= htmlspecialchars($full_name) ?> (<?= ucfirst($user_role) ?>)
    </div>

    <div class="table-container">
        <?php if ($result->num_rows > 0): ?>
            <table>
                <thead>
                    <tr>
                        <th>RC Date</th>
                        <th>RC Code</th>
                        <th>Sender (From Project)</th>
                        <th>Receiver (Warehouse)</th>
                        <th>Project</th>
                        <th>Vehicle No</th>
                        <th>Items</th>
                        <th>Total Qty</th>
                        <th>Total Value (₹)</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                <?php while ($row = $result->fetch_assoc()): ?>
                    <tr>
                        <td><?= date('d M Y', strtotime($row['rc_date'])) ?></td>
                        <td><strong><?= htmlspecialchars($row['rc_code']) ?></strong></td>
                        <td><?= htmlspecialchars($row['sender_name'] ?: '—') ?></td>
                        <td><?= htmlspecialchars($row['receiver_name']) ?></td>
                        <td>
                            <?php if ($row['project_code']): ?>
                                <strong><?= htmlspecialchars($row['project_code']) ?></strong><br>
                                <small><?= htmlspecialchars($row['project_name']) ?></small>
                            <?php else: ?>
                                <em>—</em>
                            <?php endif; ?>
                        </td>
                        <td><?= htmlspecialchars($row['vehicle_no'] ?: '—') ?></td>
                        <td><?= $row['item_count'] ?></td>
                        <td><?= number_format($row['total_qty'], 3) ?></td>
                        <td>₹ <?= number_format($row['total_value'], 2) ?></td>
                        <td>
                            <span class="status-badge status-<?= htmlspecialchars($row['status']) ?>">
                                <?= htmlspecialchars($row['status']) ?>
                            </span>
                        </td>
                        <td>
                            <a href="project-dc-view.php?id=<?= $row['id'] ?>" class="action-link">
                                <i class="fas fa-eye"></i> View
                            </a>
                            <a href="project-dc-print.php?id=<?= $row['id'] ?>" class="action-link" target="_blank">
                                <i class="fas fa-print"></i> Print
                            </a>
                        </td>
                    </tr>
                <?php endwhile; ?>
                </tbody>
            </table>
        <?php else: ?>
            <div class="no-records">
                <i class="fas fa-undo"></i>
                <h2>No Return Challans Yet</h2>
                <p>Click on "Create New Return Challan" to record material returns from projects.</p>
            </div>
        <?php endif; ?>
    </div>
</div>

</body>
</html>

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