<?php
session_start();
if(!isset($_SESSION['admin_id'])) { header("Location: index.php"); exit; }
require '../includes/db.php';

// 1. Check if ID is provided
if(!isset($_GET['id'])) { header("Location: dashboard.php"); exit; }
$id = $_GET['id'];

// 2. Fetch current data
$stmt = $pdo->prepare("SELECT * FROM portfolio WHERE id = ?");
$stmt->execute([$id]);
$item = $stmt->fetch();

if(!$item) { die("Item not found"); }

// 3. Handle Update Form Submission
if(isset($_POST['update'])) {
    $title = $_POST['title'];
    $category_id = $_POST['category_id'];
    
    // Optional: Logic to replace image could go here, 
    // but for simplicity, we usually just update text data 
    // or require re-upload for media changes.
    
    $update = $pdo->prepare("UPDATE portfolio SET title = ?, category_id = ? WHERE id = ?");
    $update->execute([$title, $category_id, $id]);
    
    header("Location: dashboard.php?msg=updated");
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Edit Project</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 min-h-screen flex items-center justify-center">
    <div class="bg-white p-8 rounded-xl shadow-lg w-full max-w-md">
        <h2 class="text-2xl font-bold mb-6 text-gray-800">Edit Project</h2>
        
        <form method="POST">
            <label class="block text-gray-600 mb-2">Project Title</label>
            <input type="text" name="title" value="<?php echo htmlspecialchars($item['title']); ?>" class="w-full mb-4 p-3 border rounded focus:outline-none focus:border-purple-500" required>
            
            <label class="block text-gray-600 mb-2">Category</label>
            <select name="category_id" class="w-full mb-6 p-3 border rounded focus:outline-none focus:border-purple-500">
                <option value="1" <?php if($item['category_id'] == 1) echo 'selected'; ?>>Graphic Design</option>
                <option value="2" <?php if($item['category_id'] == 2) echo 'selected'; ?>>Video Editing</option>
            </select>
            
            <p class="text-sm text-gray-500 mb-2">Current Media File:</p>
            <div class="mb-6 p-2 bg-gray-100 rounded text-xs truncate">
                <?php echo $item['media_file']; ?>
            </div>

            <div class="flex gap-4">
                <button type="submit" name="update" class="flex-1 bg-purple-600 text-white py-3 rounded hover:bg-purple-700 transition">Save Changes</button>
                <a href="dashboard.php" class="flex-1 bg-gray-300 text-gray-700 text-center py-3 rounded hover:bg-gray-400 transition">Cancel</a>
            </div>
        </form>
    </div>
</body>
</html>