<?php
session_start();
require_once('config.php');

if (!is_logged_in()) {
    redirect(BASE_URL . 'login.php');
}

$user = get_current_user();
if (!$user || !is_array($user)) {
    $user = ['id' => $_SESSION['user_id'] ?? null, 'username' => $_SESSION['username'] ?? 'User', 'garage_name' => 'My Garage'];
}

$document = null;
$error = '';
$success = '';
$doc_id = $_GET['id'] ?? null;

if (!$doc_id) {
    $error = 'No document specified';
} else {
    try {
        global $pdo;
        $stmt = $pdo->prepare("SELECT id, filename, uploaded_by, status, created_at FROM documents WHERE id = ? AND user_id = ?");
        $stmt->execute([$doc_id, $user['id']]);
        $document = $stmt->fetch();

        if (!$document) {
            $error = 'Document not found';
        }
    } catch (Exception $e) {
        $error = 'Error loading document: ' . $e->getMessage();
    }
}

// Handle allocation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'allocate' && $document) {
    $customer_name = trim($_POST['customer_name'] ?? '');
    $car_make = trim($_POST['car_make'] ?? '');
    $car_model = trim($_POST['car_model'] ?? '');
    $car_vin = trim($_POST['car_vin'] ?? '');

    if (empty($customer_name) || empty($car_make) || empty($car_model)) {
        $error = 'Please fill in all required fields';
    } else {
        try {
            global $pdo;
            $stmt = $pdo->prepare("
                UPDATE documents
                SET status = 'allocated',
                    customer_name = ?,
                    car_make = ?,
                    car_model = ?,
                    car_vin = ?
                WHERE id = ? AND user_id = ?
            ");
            $stmt->execute([$customer_name, $car_make, $car_model, $car_vin, $doc_id, $user['id']]);
            $success = 'Document allocated successfully!';

            // Refresh document data
            $stmt = $pdo->prepare("SELECT id, filename, uploaded_by, status, created_at, customer_name, car_make, car_model, car_vin FROM documents WHERE id = ? AND user_id = ?");
            $stmt->execute([$doc_id, $user['id']]);
            $document = $stmt->fetch();
        } catch (Exception $e) {
            $error = 'Error allocating document: ' . $e->getMessage();
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'logout') {
    session_destroy();
    redirect(BASE_URL . 'login.php');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>View Document - Document Signing System</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 10px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
            overflow: hidden;
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .header h1 {
            font-size: 28px;
            margin: 0;
        }
        .user-info {
            text-align: right;
        }
        .user-info p {
            margin: 5px 0;
            font-size: 14px;
        }
        .logout-btn {
            background: #ff6b6b;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-weight: 600;
            margin-top: 10px;
            font-size: 14px;
        }
        .logout-btn:hover {
            background: #ff5252;
        }
        .nav-menu {
            background: #f8f9fa;
            padding: 15px 30px;
            border-bottom: 1px solid #ddd;
            display: flex;
            gap: 20px;
        }
        .nav-menu a {
            color: #667eea;
            text-decoration: none;
            font-weight: 600;
            padding: 10px 15px;
            border-bottom: 2px solid transparent;
        }
        .nav-menu a:hover, .nav-menu a.active {
            border-bottom-color: #667eea;
        }
        .content {
            padding: 40px;
        }
        .back-link {
            display: inline-block;
            margin-bottom: 20px;
            color: #667eea;
            text-decoration: none;
            font-weight: 600;
        }
        .back-link:hover {
            text-decoration: underline;
        }
        .alert {
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .alert-error {
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
        .alert-success {
            background: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }
        .doc-sections {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
        }
        .section {
            background: #f8f9fa;
            padding: 30px;
            border-radius: 8px;
        }
        .section h3 {
            color: #333;
            margin-bottom: 20px;
            font-size: 18px;
        }
        .doc-info {
            display: grid;
            gap: 15px;
        }
        .info-item {
            background: white;
            padding: 15px;
            border-radius: 5px;
            border: 1px solid #ddd;
        }
        .info-label {
            color: #999;
            font-size: 12px;
            text-transform: uppercase;
            margin-bottom: 5px;
        }
        .info-value {
            color: #333;
            font-size: 16px;
            font-weight: 600;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: #333;
            font-weight: 600;
            font-size: 14px;
        }
        .form-group input {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }
        .form-group input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 5px;
            cursor: pointer;
            font-weight: 600;
            text-decoration: none;
            display: inline-block;
            margin-right: 10px;
            font-size: 14px;
        }
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 20px rgba(102, 126, 234, 0.4);
        }
        .btn-secondary {
            background: #6c757d;
        }
        .btn-secondary:hover {
            box-shadow: 0 5px 20px rgba(108, 117, 125, 0.4);
        }
        .status-badge {
            padding: 8px 15px;
            border-radius: 5px;
            font-size: 14px;
            font-weight: 600;
            display: inline-block;
        }
        .status-pending {
            background: #fff3cd;
            color: #856404;
        }
        .status-allocated {
            background: #cfe2ff;
            color: #084298;
        }
        .status-signed {
            background: #d4edda;
            color: #155724;
        }
        @media (max-width: 768px) {
            .doc-sections {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📄 View Document</h1>
            <div class="user-info">
                <p><strong><?php echo htmlspecialchars($user['garage_name']); ?></strong></p>
                <p><?php echo htmlspecialchars($user['username']); ?></p>
                <form method="POST" style="display: inline;">
                    <input type="hidden" name="action" value="logout">
                    <button type="submit" class="logout-btn">Logout</button>
                </form>
            </div>
        </div>

        <div class="nav-menu">
            <a href="<?php echo BASE_URL; ?>admin-dashboard.php">Dashboard</a>
            <a href="<?php echo BASE_URL; ?>documents.php" class="active">Documents</a>
            <a href="<?php echo BASE_URL; ?>upload.php">Upload Document</a>
        </div>

        <div class="content">
            <a href="<?php echo BASE_URL; ?>documents.php" class="back-link">← Back to Documents</a>

            <?php if ($error): ?>
                <div class="alert alert-error"><?php echo htmlspecialchars($error); ?></div>
            <?php endif; ?>

            <?php if ($success): ?>
                <div class="alert alert-success"><?php echo htmlspecialchars($success); ?></div>
            <?php endif; ?>

            <?php if ($document): ?>
                <div class="doc-sections">
                    <!-- Document Info -->
                    <div class="section">
                        <h3>📋 Document Details</h3>
                        <div class="doc-info">
                            <div class="info-item">
                                <div class="info-label">Filename</div>
                                <div class="info-value"><?php echo htmlspecialchars($document['filename']); ?></div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">Uploaded By</div>
                                <div class="info-value"><?php echo htmlspecialchars($document['uploaded_by']); ?></div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">Upload Date</div>
                                <div class="info-value"><?php echo date('M d, Y g:i A', strtotime($document['created_at'])); ?></div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">Current Status</div>
                                <div class="info-value">
                                    <span class="status-badge status-<?php echo htmlspecialchars($document['status']); ?>">
                                        <?php echo ucfirst(htmlspecialchars($document['status'])); ?>
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Allocation Form (only show if not signed) -->
                    <?php if ($document['status'] !== 'signed'): ?>
                    <div class="section">
                        <h3>🔗 Allocate to Car & Customer</h3>
                        <form method="POST">
                            <input type="hidden" name="action" value="allocate">

                            <div class="form-group">
                                <label for="customer_name">Customer Name *</label>
                                <input type="text" id="customer_name" name="customer_name" required value="<?php echo htmlspecialchars($document['customer_name'] ?? ''); ?>">
                            </div>

                            <div class="form-group">
                                <label for="car_make">Car Make *</label>
                                <input type="text" id="car_make" name="car_make" placeholder="e.g., Ford, Toyota" required value="<?php echo htmlspecialchars($document['car_make'] ?? ''); ?>">
                            </div>

                            <div class="form-group">
                                <label for="car_model">Car Model *</label>
                                <input type="text" id="car_model" name="car_model" placeholder="e.g., F-150, Camry" required value="<?php echo htmlspecialchars($document['car_model'] ?? ''); ?>">
                            </div>

                            <div class="form-group">
                                <label for="car_vin">VIN (Optional)</label>
                                <input type="text" id="car_vin" name="car_vin" placeholder="Vehicle Identification Number" value="<?php echo htmlspecialchars($document['car_vin'] ?? ''); ?>">
                            </div>

                            <button type="submit" class="btn">Allocate Document</button>
                        </form>
                    </div>
                    <?php endif; ?>

                    <!-- Allocated Info (if allocated) -->
                    <?php if (!empty($document['customer_name'])): ?>
                    <div class="section">
                        <h3>✅ Allocated To</h3>
                        <div class="doc-info">
                            <div class="info-item">
                                <div class="info-label">Customer</div>
                                <div class="info-value"><?php echo htmlspecialchars($document['customer_name']); ?></div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">Vehicle</div>
                                <div class="info-value"><?php echo htmlspecialchars($document['car_make'] . ' ' . $document['car_model']); ?></div>
                            </div>
                            <?php if (!empty($document['car_vin'])): ?>
                            <div class="info-item">
                                <div class="info-label">VIN</div>
                                <div class="info-value"><?php echo htmlspecialchars($document['car_vin']); ?></div>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>