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

// Only Store Manager / Admin can approve/reject GRNs
// $allowed_roles = ['store manager', 'admin'];
// 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'] ?? 'Approver';

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

// Fetch GRN details + verify it's in approvable status
$grn_query = "
    SELECT 
        grn.*,
        p.project_code, p.project_name,
        po.id AS po_ref_id,
        u.full_name AS received_by_name
    FROM goods_received_note grn
    LEFT JOIN project_master p ON grn.project_id = p.id
    LEFT JOIN purchase_order po ON grn.po_id = po.id
    LEFT JOIN users u ON grn.received_by = u.id
    WHERE grn.id = ? AND grn.status IN ('Received', 'Pending Verification')
";
$grn_stmt = $conn->prepare($grn_query);
$grn_stmt->bind_param("i", $grn_id);
$grn_stmt->execute();
$grn = $grn_stmt->get_result()->fetch_assoc();

if (!$grn) {
    die("<h2 style='color:#ef4444;text-align:center;padding:100px;'>
        GRN not found, already verified/processed, or cannot be approved/rejected.
    </h2>");
}

// Fetch GRN items
$items_query = "
    SELECT 
        gri.received_qty, gri.rate, gri.batch_no, gri.unit,
        (gri.received_qty * gri.rate) AS line_total,
        i.name AS item_name
    FROM goods_received_note_items gri
    INNER JOIN inventory_master i ON gri.item_id = i.id
    WHERE gri.grn_id = ?
    ORDER BY i.name ASC
";
$items_stmt = $conn->prepare($items_query);
$items_stmt->bind_param("i", $grn_id);
$items_stmt->execute();
$items_result = $items_stmt->get_result();

// Calculate grand total for display
$grand_total = 0;
while ($item = $items_result->fetch_assoc()) {
    $grand_total += $item['line_total'];
}
$items_result->data_seek(0); // reset for display

$success = "";
$error = "";

// Handle approve/reject
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $action = $_POST['action'] ?? ''; // 'approve' or 'reject'
    $comments = trim($_POST['comments'] ?? '');

    if (!in_array($action, ['approve', 'reject'])) {
        $error = "Invalid action.";
    } else {
        $new_status = $action === 'approve' ? 'Verified' : 'Rejected';

        try {
            $conn->begin_transaction();

            $update = "
                UPDATE goods_received_note 
                SET 
                    status = ?,
                    approved_by = ?,
                    approved_at = NOW(),
                    approval_comments = ?
                WHERE id = ? AND status IN ('Received', 'Pending Verification')
            ";
            $stmt = $conn->prepare($update);
            $stmt->bind_param("sisi", $new_status, $user_id, $comments, $grn_id);

            if ($stmt->execute() && $stmt->affected_rows > 0) {
                $success = "GRN #$grn_id has been " . ($action === 'approve' ? 'Verified' : 'Rejected') . " successfully!";
            } else {
                $error = "Failed to update GRN (may already be processed).";
            }

            $conn->commit();
        } catch (Exception $e) {
            $conn->rollback();
            $error = "Error: " . $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Verify / Reject GRN #<?= str_pad($grn_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: #8b5cf6;
            --success: #22c55e;
            --danger: #ef4444;
            --glass: rgba(255,255,255,0.08);
            --border: rgba(255,255,255,0.15);
        }
        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: 1000px; margin: 0 auto; }
        .back {
            color: #c4b5fd;
            text-decoration: none;
            font-weight: 500;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 20px;
        }
        .back:hover { color: white; }

        h1 { margin: 0 0 8px; font-size: 2rem; }
        .grn-info { opacity: 0.9; margin-bottom: 30px; font-size: 1.1rem; }

        .detail-card {
            background: var(--glass);
            backdrop-filter: blur(12px);
            border: 1px solid var(--border);
            border-radius: 16px;
            padding: 28px;
            margin-bottom: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.4);
        }
        .detail-row {
            display: flex;
            flex-wrap: wrap;
            margin-bottom: 18px;
            gap: 20px;
        }
        .detail-label {
            font-weight: 600;
            min-width: 160px;
            opacity: 0.85;
        }
        .detail-value { flex: 1; }

        .items-table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }
        .items-table th, .items-table td {
            padding: 14px 18px;
            border-bottom: 1px solid var(--border);
            text-align: left;
        }
        .items-table th { background: rgba(255,255,255,0.1); font-weight: 600; }

        .action-buttons {
            margin-top: 40px;
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
        }
        .btn {
            padding: 14px 28px;
            border-radius: 12px;
            text-decoration: none;
            font-weight: 600;
            font-size: 1.1rem;
            display: inline-flex;
            align-items: center;
            gap: 10px;
            transition: all 0.3s;
            border: none;
            cursor: pointer;
        }
        .btn-approve { background: var(--success); color: white; }
        .btn-approve:hover { background: #16a34a; }
        .btn-reject { background: var(--danger); color: white; }
        .btn-reject:hover { background: #dc2626; }
        .btn-secondary { background: rgba(255,255,255,0.15); color: white; }
        .btn-secondary:hover { background: rgba(255,255,255,0.25); }

        textarea {
            width: 100%;
            padding: 14px;
            background: rgba(255,255,255,0.08);
            border: 1px solid var(--border);
            border-radius: 10px;
            color: white;
            min-height: 120px;
            margin-bottom: 15px;
        }
        .message {
            padding: 16px;
            border-radius: 10px;
            margin-bottom: 25px;
            font-weight: 500;
        }
        .success { background: rgba(34,197,94,0.25); color: #86efac; }
        .error { background: rgba(239,68,68,0.25); color: #fca5a5; }
    </style>
</head>
<body>

<div class="container">
    <a href="grn_list.php<?= $grn['project_id'] ? "?project_id={$grn['project_id']}" : "" ?>" class="back">
        <i class="fas fa-arrow-left"></i> Back to GRN List
    </a>

    <h1>Verify / Reject GRN #<?= str_pad($grn_id, 5, '0', STR_PAD_LEFT) ?></h1>
    <div class="grn-info">
        Vendor: <strong><?= htmlspecialchars($grn['vendor']) ?></strong><br>
        <?php if ($grn['project_name']): ?>
            Project: <?= htmlspecialchars($grn['project_name']) ?> (<?= htmlspecialchars($grn['project_code']) ?>)
        <?php else: ?>
            Central Stock / General Receipt
        <?php endif; ?>
    </div>

    <div class="detail-card">
        <div class="detail-row">
            <div class="detail-label">GRN Date:</div>
            <div class="detail-value"><?= date('d M Y', strtotime($grn['grn_date'])) ?></div>
        </div>

        <div class="detail-row">
            <div class="detail-label">PO Reference:</div>
            <div class="detail-value">
                <?= $grn['po_id'] ? 'PO-' . str_pad($grn['po_id'], 5, '0', STR_PAD_LEFT) : '—' ?>
            </div>
        </div>

        <div class="detail-row">
            <div class="detail-label">Invoice / DC No:</div>
            <div class="detail-value"><?= htmlspecialchars($grn['invoice_number'] ?: '—') ?></div>
        </div>

        <div class="detail-row">
            <div class="detail-label">Status:</div>
            <div class="detail-value">
                <span style="padding:8px 16px;background:rgba(245,158,11,0.25);border-radius:20px;font-weight:600;">
                    <?= htmlspecialchars($grn['status']) ?>
                </span>
            </div>
        </div>

        <div class="detail-row">
            <div class="detail-label">Received By:</div>
            <div class="detail-value"><?= htmlspecialchars($grn['received_by_name'] ?? '—') ?></div>
        </div>
    </div>

    <div class="section-title">Received Items</div>
    <div class="detail-card">
        <?php if ($items_result->num_rows > 0): ?>
            <table class="items-table">
                <thead>
                    <tr>
                        <th>Item Name</th>
                        <th>Received Qty</th>
                        <th>Rate (₹)</th>
                        <th>Batch/Lot</th>
                        <th>Unit</th>
                        <th>Line Total (₹)</th>
                    </tr>
                </thead>
                <tbody>
                <?php 
                $counter = 1;
                $grand_total = 0;
                while ($item = $items_result->fetch_assoc()): 
                    $line_total = $item['received_qty'] * $item['rate'];
                    $grand_total += $line_total;
                ?>
                    <tr>
                        <td><?= htmlspecialchars($item['item_name']) ?></td>
                        <td><?= number_format($item['received_qty'], 3) ?></td>
                        <td>₹ <?= number_format($item['rate'], 2) ?></td>
                        <td><?= htmlspecialchars($item['batch_no'] ?: '—') ?></td>
                        <td><?= htmlspecialchars($item['unit']) ?></td>
                        <td>₹ <?= number_format($line_total, 2) ?></td>
                    </tr>
                <?php endwhile; ?>
                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="5" style="text-align:right;font-weight:700;">Grand Total Value:</td>
                        <td style="font-weight:700;">₹ <?= number_format($grand_total, 2) ?></td>
                    </tr>
                </tfoot>
            </table>
        <?php else: ?>
            <p style="text-align:center; opacity:0.8;">No items in this GRN.</p>
        <?php endif; ?>
    </div>

    <?php if (!empty($grn['remarks'])): ?>
        <div class="section-title">Remarks / Delivery Notes</div>
        <div class="detail-card">
            <div style="white-space: pre-wrap; line-height: 1.6;">
                <?= nl2br(htmlspecialchars($grn['remarks'])) ?>
            </div>
        </div>
    <?php endif; ?>

    <div class="section-title">Verification Action</div>
    <div class="detail-card">
        <form method="post">
            <div class="form-group">
                <label for="comments">Verification / Rejection Comments (optional)</label>
                <textarea name="comments" id="comments" placeholder="Reason for rejection, notes for store team..."></textarea>
            </div>

            <div class="action-buttons">
                <button type="submit" name="action" value="approve" class="btn btn-approve">
                    <i class="fas fa-check-circle"></i> Verify GRN
                </button>

                <button type="submit" name="action" value="reject" class="btn btn-reject">
                    <i class="fas fa-times-circle"></i> Reject GRN
                </button>

                <a href="grn_list.php<?= $grn['project_id'] ? "?project_id={$grn['project_id']}" : "" ?>" class="btn btn-secondary">
                    <i class="fas fa-arrow-left"></i> Cancel
                </a>
            </div>
        </form>
    </div>

    <?php if ($success): ?>
        <div class="message success" style="margin-top:30px;">
            <i class="fas fa-check-circle"></i> <?= $success ?>
        </div>
    <?php endif; ?>

    <?php if ($error): ?>
        <div class="message error" style="margin-top:30px;">
            <i class="fas fa-exclamation-triangle"></i> <?= $error ?>
        </div>
    <?php endif; ?>
</div>

</body>
</html>

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