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

// Only Store Manager / Admin can approve/reject
// $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';

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

// Fetch PR details + verify it's Pending
$pr_query = "
    SELECT 
        pr.*,
        p.project_code, p.project_name,
        u.full_name AS raised_by
    FROM procurement_request pr
    LEFT JOIN project_master p ON pr.project_id = p.id
    LEFT JOIN users u ON pr.requested_by = u.id
    WHERE pr.id = ? AND pr.status = 'Pending'
";
$pr_stmt = $conn->prepare($pr_query);
$pr_stmt->bind_param("i", $pr_id);
$pr_stmt->execute();
$pr = $pr_stmt->get_result()->fetch_assoc();

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

// Fetch PR items
$items_query = "
    SELECT 
        pri.requested_qty, pri.unit,
        i.name AS item_name
    FROM procurement_request_items pri
    INNER JOIN inventory_master i ON pri.item_id = i.id
    WHERE pri.pr_id = ?
    ORDER BY i.name ASC
";
$items_stmt = $conn->prepare($items_query);
$items_stmt->bind_param("i", $pr_id);
$items_stmt->execute();
$items_result = $items_stmt->get_result();

$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' ? 'Approved' : 'Rejected';

        try {
            $conn->begin_transaction();

            $update = "
                UPDATE procurement_request 
                SET status = ?, approved_by = ?, approved_at = NOW(), approval_comments = ?
                WHERE id = ? AND status = 'Pending'
            ";
            $stmt = $conn->prepare($update);
            $stmt->bind_param("sisi", $new_status, $user_id, $comments, $pr_id);
            $stmt->execute();

            if ($stmt->affected_rows > 0) {
                $success = "PR #$pr_id has been " . ($action === 'approve' ? 'Approved' : 'Rejected') . " successfully!";
            } else {
                $error = "Failed to update (PR 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>Approve / Reject PR #<?= str_pad($pr_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; }
        .pr-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="pr_approval_list.php" class="back">
        <i class="fas fa-arrow-left"></i> Back to Pending PRs
    </a>

    <h1>Review & Approve / Reject PR #<?= str_pad($pr_id, 5, '0', STR_PAD_LEFT) ?></h1>
    <div class="pr-info">
        Raised by: <strong><?= htmlspecialchars($pr['raised_by']) ?></strong><br>
        Project: <?= $pr['project_name'] ? htmlspecialchars($pr['project_name']) . ' (' . htmlspecialchars($pr['project_code']) . ')' : 'Central Request' ?><br>
        PR Date: <?= date('d M Y', strtotime($pr['pr_date'])) ?>
        <?php if ($pr['required_by_date']): ?>
            • Required by: <?= date('d M Y', strtotime($pr['required_by_date'])) ?>
        <?php endif; ?>
    </div>

    <div class="detail-card">
        <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;">
                    Pending Approval
                </span>
            </div>
        </div>

        <?php if (!empty($pr['remarks'])): ?>
            <div class="detail-row">
                <div class="detail-label">Remarks from Site:</div>
                <div class="detail-value" style="white-space: pre-wrap;">
                    <?= nl2br(htmlspecialchars($pr['remarks'])) ?>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <div class="section-title">Requested Items</div>
    <div class="detail-card">
        <?php if ($items_result->num_rows > 0): ?>
            <table class="items-table">
                <thead>
                    <tr>
                        <th>Item Name</th>
                        <th>Requested Qty</th>
                        <th>Unit</th>
                    </tr>
                </thead>
                <tbody>
                <?php while ($item = $items_result->fetch_assoc()): ?>
                    <tr>
                        <td><?= htmlspecialchars($item['item_name']) ?></td>
                        <td><?= number_format($item['requested_qty'], 2) ?></td>
                        <td><?= htmlspecialchars($item['unit']) ?></td>
                    </tr>
                <?php endwhile; ?>
                </tbody>
            </table>
        <?php else: ?>
            <p style="text-align:center; opacity:0.8;">No items in this PR.</p>
        <?php endif; ?>
    </div>

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

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

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

                <a href="pr_approval_list.php" 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
$pr_stmt->close();
$items_stmt->close();
$conn->close();
?>