<?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'];
}

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['document'])) {
    $file = $_FILES['document'];

    if ($file['error'] === UPLOAD_ERR_OK) {
        $filename = basename($file['name']);
        $upload_dir = dirname(__FILE__) . '/uploads/documents/';

        // Create upload directory if it doesn't exist
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }

        // Sanitize filename
        $filename = preg_replace("/[^a-zA-Z0-9._-]/", "_", $filename);
        $filepath = $upload_dir . time() . '_' . $filename;

        if (move_uploaded_file($file['tmp_name'], $filepath)) {
            try {
                global $pdo;
                $stmt = $pdo->prepare("
                    INSERT INTO documents (user_id, filename, uploaded_by, status, created_at)
                    VALUES (?, ?, ?, 'pending', NOW())
                ");

                if ($stmt->execute([$user['id'], $filename, $user['username']])) {
                    $success = 'Document uploaded successfully!';
                    // Redirect after 2 seconds
                    echo "<script>setTimeout(function() { window.location.href = '" . BASE_URL . "documents.php'; }, 2000);</script>";
                } else {
                    $error = 'Error saving document to database';
                    unlink($filepath);
                }
            } catch (Exception $e) {
                $error = 'Database error: ' . $e->getMessage();
                unlink($filepath);
            }
        } else {
            $error = 'Error uploading file. Please try again.';
        }
    } else {
        $error = 'File upload error. Please select a file.';
    }
}

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>Upload 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, .nav-menu button {
            color: #667eea;
            text-decoration: none;
            font-weight: 600;
            padding: 10px 15px;
            border: none;
            background: none;
            cursor: pointer;
            border-bottom: 2px solid transparent;
        }
        .nav-menu a:hover, .nav-menu a.active {
            border-bottom-color: #667eea;
        }
        .content {
            padding: 40px;
            max-width: 600px;
        }
        .upload-form {
            background: #f8f9fa;
            padding: 30px;
            border-radius: 8px;
            border: 2px dashed #667eea;
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: 600;
        }
        .file-input-wrapper {
            position: relative;
            overflow: hidden;
            display: inline-block;
            width: 100%;
        }
        .file-input-label {
            display: block;
            padding: 20px;
            background: white;
            border: 2px dashed #667eea;
            border-radius: 5px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
        }
        .file-input-label:hover {
            background: #f0f4ff;
        }
        #document {
            display: none;
        }
        .file-name {
            color: #667eea;
            font-weight: 600;
            margin-top: 10px;
        }
        .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;
        }
        button[type="submit"] {
            width: 100%;
            padding: 12px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 5px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            margin-top: 20px;
        }
        button[type="submit"]:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 20px rgba(102, 126, 234, 0.4);
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📤 Upload 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">Documents</a>
            <a href="<?php echo BASE_URL; ?>upload.php" class="active">Upload Document</a>
        </div>

        <div class="content">
            <?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; ?>

            <form method="POST" enctype="multipart/form-data" class="upload-form">
                <div class="form-group">
                    <label>Select Document to Upload</label>
                    <div class="file-input-wrapper">
                        <label for="document" class="file-input-label">
                            <div>📁 Click to select file or drag & drop</div>
                            <div style="font-size: 12px; color: #999; margin-top: 5px;">PDF, DOC, DOCX (Max 5MB)</div>
                        </label>
                        <input type="file" id="document" name="document" accept=".pdf,.doc,.docx" required>
                    </div>
                    <div id="fileName" class="file-name"></div>
                </div>

                <button type="submit">Upload Document</button>
            </form>
        </div>
    </div>

    <script>
        const fileInput = document.getElementById('document');
        const fileLabel = document.querySelector('.file-input-label');
        const fileName = document.getElementById('fileName');

        fileInput.addEventListener('change', function() {
            if (this.files.length > 0) {
                fileName.textContent = 'Selected: ' + this.files[0].name;
            }
        });

        fileLabel.addEventListener('dragover', function(e) {
            e.preventDefault();
            this.style.background = '#f0f4ff';
        });

        fileLabel.addEventListener('dragleave', function(e) {
            e.preventDefault();
            this.style.background = 'white';
        });

        fileLabel.addEventListener('drop', function(e) {
            e.preventDefault();
            this.style.background = 'white';
            if (e.dataTransfer.files.length > 0) {
                fileInput.files = e.dataTransfer.files;
                fileName.textContent = 'Selected: ' + e.dataTransfer.files[0].name;
            }
        });
    </script>
</body>
</html>