<?php
// Start session and DB connection
session_start();
require_once 'db.php';

// Check login
if (!isset($_SESSION['logged_in_user'])) {
    header("Location: user-login.php");
    exit;
}

$loggedInUser = $_SESSION['logged_in_user'];

// Get numeric ID and permission flag
$stmt = $pdo->prepare("SELECT id, can_upload_backgrounds FROM users WHERE user_id = ?");
$stmt->execute([$loggedInUser]);
$user = $stmt->fetch();

if (!$user || $user['can_upload_backgrounds'] != 1) {
    die("You do not have permission to upload backgrounds.");
}

$uploadSuccess = false;
$errorMessage = "";

// Handle upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['background_image'])) {
    $file = $_FILES['background_image'];

    // Validate file type
    $allowedTypes = ['image/jpeg', 'image/jpg'];
    if (!in_array($file['type'], $allowedTypes)) {
        $errorMessage = "Only .jpg files are allowed.";
    } elseif ($file['size'] > 200 * 1024) {
        $errorMessage = "Image must be under 200 KB.";
    } elseif (!getimagesize($file['tmp_name'])) {
        $errorMessage = "Uploaded file is not a valid image.";
    } else {
        // Sanitize and rename
        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        $safeName = 'bg_' . time() . '_' . rand(1000,9999) . '.' . $ext;
        $targetPath = __DIR__ . '/assets/backgrounds/' . $safeName;

        if (move_uploaded_file($file['tmp_name'], $targetPath)) {
            $uploadSuccess = true;
        } else {
            $errorMessage = "Upload failed. Please try again.";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Upload Background Image</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light py-4">

<div class="container">
    <h2 class="mb-4">Upload a Background Image</h2>

    <?php if ($uploadSuccess): ?>
        <div class="alert alert-success">Image uploaded successfully! You can now select it in your lead capture form.</div>
    <?php elseif (!empty($errorMessage)): ?>
        <div class="alert alert-danger"><?php echo htmlspecialchars($errorMessage); ?></div>
    <?php endif; ?>

    <form method="POST" enctype="multipart/form-data" class="border p-4 bg-white shadow-sm rounded">
        <div class="mb-3">
            <label class="form-label">Choose a .jpg image (max 200 KB)</label>
            <input type="file" name="background_image" class="form-control" accept=".jpg" required>
        </div>
        <button type="submit" class="btn btn-primary">Upload Background</button>
        <a href="create-lead-capture.php" class="btn btn-secondary ms-2">Back</a>
    </form>
</div>

</body>
</html>
