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

$rc_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($rc_id <= 0) {
    die("<h2 style='color:red;text-align:center;padding:100px;'>Invalid Return Challan ID</h2>");
}

// Fetch Return Challan Header
$query = "
    SELECT 
        rc.*,
        p.project_code,
        p.project_name,
        u.full_name AS issued_by_name
    FROM return_challan rc
    LEFT JOIN project_master p ON rc.project_id = p.id
    LEFT JOIN users u ON rc.issued_by = u.id
    WHERE rc.id = ?
";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $rc_id);
$stmt->execute();
$rc = $stmt->get_result()->fetch_assoc();

if (!$rc) {
    die("<h2 style='color:red;text-align:center;padding:100px;'>Return Challan not found.</h2>");
}

// Fetch Items
$items_query = "
    SELECT 
        rci.*,
        i.name AS item_name,
        i.model_no AS item_model,
        i.description AS item_description,
        i.hsn_sac AS hsn_code
    FROM return_challan_items rci
    INNER JOIN inventory_master i ON rci.item_id = i.id
    WHERE rci.rc_id = ?
    ORDER BY i.name ASC
";
$items_stmt = $conn->prepare($items_query);
$items_stmt->bind_param("i", $rc_id);
$items_stmt->execute();
$items = $items_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>View Return Challan - RC-<?= str_pad($rc_id, 5, '0', STR_PAD_LEFT) ?></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: '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;
        }
        .container { max-width: 1200px; margin: 0 auto; }
        .glass {
            background: var(--glass);
            backdrop-filter: blur(16px);
            border: 1px solid var(--border);
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 15px 40px rgba(0,0,0,0.5);
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
            flex-wrap: wrap;
            gap: 15px;
        }
        h1 { margin: 0; font-size: 2.2rem; }
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 12px;
            font-weight: 600;
            cursor: pointer;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        .btn-print {
            background: #22c55e;
            color: white;
        }
        .btn-back {
            background: rgba(255,255,255,0.15);
            color: white;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
            background: rgba(0,0,0,0.2);
            border-radius: 12px;
            overflow: hidden;
        }
        th {
            background: rgba(168,85,247,0.3);
            padding: 16px;
            text-align: left;
        }
        td {
            padding: 14px 16px;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }
        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin: 25px 0;
        }
        .info-box {
            background: rgba(255,255,255,0.08);
            padding: 20px;
            border-radius: 16px;
            border: 1px solid rgba(255,255,255,0.1);
        }
        .label { font-size: 0.9rem; opacity: 0.8; margin-bottom: 5px; }
        .value { font-size: 1.1rem; font-weight: 600; }
        .total {
            font-size: 1.4rem;
            font-weight: 700;
            text-align: right;
            margin: 20px 0;
            padding: 15px;
            background: rgba(168,85,247,0.2);
            border-radius: 12px;
        }
    </style>
</head>
<body>
<?php include '../config/header.php' ?>
<div class="container">
    <div class="glass">
        <div class="header">
            <div>
                <h1><i class="fas fa-undo"></i> Return Challan Details</h1>
                <p style="opacity:0.85;">RC-<?= str_pad($rc_id, 5, '0', STR_PAD_LEFT) ?></p>
            </div>
            <div>
                <a href="return_list.php" class="btn btn-back">
                    <i class="fas fa-arrow-left"></i> Back to List
                </a>
                <a href="project-dc-print.php?id=<?= $rc_id ?>" target="_blank" class="btn btn-print">
                    <i class="fas fa-print"></i> Print Challan
                </a>
            </div>
        </div>

        <!-- Basic Info -->
        <div class="info-grid">
            <div class="info-box">
                <div class="label">RC Date</div>
                <div class="value"><?= date('d M Y', strtotime($rc['rc_date'])) ?></div>
            </div>
            <div class="info-box">
                <div class="label">Status</div>
                <div class="value" style="color:#86efac;"><?= htmlspecialchars($rc['status']) ?></div>
            </div>
            <div class="info-box">
                <div class="label">Project</div>
                <div class="value">
                    <?= htmlspecialchars($rc['project_code'] ?? '') ?> - 
                    <?= htmlspecialchars($rc['project_name'] ?? 'N/A') ?>
                </div>
            </div>
        </div>

        <!-- Parties Info -->
        <div class="info-grid">
            <div class="info-box">
                <div class="label">Sender (From Project)</div>
                <div class="value"><?= htmlspecialchars($rc['sender_name']) ?></div>
            </div>
            <div class="info-box">
                <div class="label">Receiver (At Warehouse)</div>
                <div class="value"><?= htmlspecialchars($rc['receiver_name']) ?></div>
            </div>
            <div class="info-box">
                <div class="label">Vehicle Number</div>
                <div class="value"><?= htmlspecialchars($rc['vehicle_no'] ?: '—') ?></div>
            </div>
        </div>

        <!-- Items Table -->
        <h2 style="margin:25px 0 15px;">Returned Items</h2>
        <table>
            <thead>
                <tr>
                    <th>Sr.No</th>
                    <th>Item Name</th>
                    <th>Model No</th>
                    <th>Serial No</th>
                    <th>Description</th>
                    <th>Returned Qty</th>
                    <th>Unit</th>
                    <th>Rate (₹)</th>
                    <th>Amount (₹)</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                $grand_total = 0;
                $sr = 1;
                foreach ($items as $item): 
                    $line_total = $item['returned_qty'] * ($item['rate'] ?? 0);
                    $grand_total += $line_total;
                ?>
                <tr>
                    <td><?= $sr++ ?></td>
                    <td><strong><?= htmlspecialchars($item['item_name']) ?></strong></td>
                    <td><?= htmlspecialchars($item['item_model'] ?: '—') ?></td>
                    <td><?= htmlspecialchars($item['serial_no'] ?: '—') ?></td>
                    <td><?= htmlspecialchars($item['item_description'] ?: '—') ?></td>
                    <td><?= number_format($item['returned_qty'], 3) ?></td>
                    <td><?= htmlspecialchars($item['uom']) ?></td>
                    <td><?= number_format($item['rate'] ?? 0, 2) ?></td>
                    <td><?= number_format($line_total, 2) ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <div class="total">
            Grand Total : ₹ <?= number_format($grand_total, 2) ?>
        </div>

        <?php if (!empty($rc['remarks'])): ?>
        <div style="margin-top:25px; padding:20px; background:rgba(255,255,255,0.08); border-radius:12px;">
            <strong>Remarks:</strong><br>
            <?= nl2br(htmlspecialchars($rc['remarks'])) ?>
        </div>
        <?php endif; ?>

        <div style="margin-top:30px; text-align:center; opacity:0.8;">
            Generated on <?= date('d M Y h:i A') ?> | Issued By: <?= htmlspecialchars($rc['issued_by_name'] ?? 'System') ?>
        </div>
    </div>
</div>

</body>
</html>

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