<?php
session_start();
if(!isset($_SESSION['admin_id'])) { header("Location: index.php"); exit; }
require '../includes/db.php';

$msg = "";

// 1. Handle New Upload
if(isset($_POST['upload'])) {
    $title = $_POST['title'];
    $category_id = $_POST['category_id'];
    $media_type = $_POST['media_type'];
    
    // File Upload Logic
    $targetDir = "../assets/uploads/";
    
    // Generate a unique name to prevent overwriting (e.g., 1709923_image.jpg)
    $fileName = time() . '_' . basename($_FILES["file"]["name"]); 
    $targetFilePath = $targetDir . $fileName;
    
    // Check file type (Basic security)
    $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
    $allowTypes = array('jpg','png','jpeg','gif','mp4','webp');
    
    if(in_array(strtolower($fileType), $allowTypes)){
        if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
            // Insert into DB
            $stmt = $pdo->prepare("INSERT INTO portfolio (title, category_id, media_file, media_type) VALUES (?, ?, ?, ?)");
            $stmt->execute([$title, $category_id, $fileName, $media_type]);
            $msg = "Project uploaded successfully!";
        } else {
            $msg = "Error uploading file.";
        }
    } else {
        $msg = "Invalid file type. Only JPG, PNG, GIF, WEBP & MP4 allowed.";
    }
}

// 2. Fetch All Items
$items = $pdo->query("SELECT p.*, c.name as cat_name FROM portfolio p JOIN categories c ON p.category_id = c.id ORDER BY p.id DESC")->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Admin Dashboard</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
</head>
<body class="bg-gray-100 min-h-screen">

    <nav class="bg-slate-900 p-4 text-white shadow-md">
        <div class="container mx-auto flex justify-between items-center">
            <h1 class="font-bold text-xl tracking-wide">Rushi<span class="text-purple-400">Admin</span></h1>
            <div class="flex items-center gap-4">
                <a href="../index.php" target="_blank" class="text-gray-400 hover:text-white text-sm">View Website</a>
                <a href="logout.php" class="bg-red-600 hover:bg-red-700 px-4 py-2 rounded text-sm transition">Logout</a>
            </div>
        </div>
    </nav>

    <div class="container mx-auto p-6 max-w-6xl">

        <?php if($msg || (isset($_GET['msg']) && $_GET['msg']=='updated')): ?>
        <div class="bg-green-100 border-l-4 border-green-500 text-green-700 p-4 mb-6 rounded shadow-sm" role="alert">
            <p class="font-bold">Success</p>
            <p><?php echo $msg ? $msg : "Project updated successfully."; ?></p>
        </div>
        <?php endif; ?>

        <div class="bg-white p-6 rounded-xl shadow-lg mb-10 border border-gray-200">
            <h2 class="text-xl font-bold mb-4 text-gray-800 flex items-center gap-2">
                <i class="fas fa-plus-circle text-purple-600"></i> Add New Work
            </h2>
            <form method="POST" enctype="multipart/form-data" class="grid gap-6 md:grid-cols-2">
                
                <div>
                    <label class="block text-sm font-medium text-gray-600 mb-1">Project Title</label>
                    <input type="text" name="title" placeholder="e.g. Real Estate Logo" class="w-full border p-3 rounded focus:outline-none focus:border-purple-500" required>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-600 mb-1">Category</label>
                    <select name="category_id" class="w-full border p-3 rounded focus:outline-none focus:border-purple-500">
                        <option value="1">Graphic Design</option>
                        <option value="2">Video Editing</option>
                    </select>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-600 mb-1">File Type</label>
                    <select name="media_type" class="w-full border p-3 rounded focus:outline-none focus:border-purple-500">
                        <option value="image">Image (JPG, PNG)</option>
                        <option value="video">Video (MP4)</option>
                    </select>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-600 mb-1">Upload File</label>
                    <input type="file" name="file" class="w-full border p-2 rounded bg-gray-50 text-sm focus:outline-none" required>
                </div>

                <button type="submit" name="upload" class="md:col-span-2 bg-purple-600 hover:bg-purple-700 text-white font-bold py-3 rounded transition shadow-md">
                    <i class="fas fa-cloud-upload-alt mr-2"></i> Upload Project
                </button>
            </form>
        </div>

        <h2 class="text-xl font-bold mb-4 text-gray-800 flex items-center gap-2">
            <i class="fas fa-layer-group text-purple-600"></i> Manage Portfolio
        </h2>
        
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <?php foreach($items as $item): ?>
            <div class="bg-white rounded-xl shadow-md overflow-hidden hover:shadow-xl transition duration-300 border border-gray-100 flex flex-col h-full">
                
                <div class="h-48 overflow-hidden bg-gray-100 relative">
                    <?php if($item['media_type'] == 'image'): ?>
                        <img src="../assets/uploads/<?php echo $item['media_file']; ?>" class="w-full h-full object-cover">
                    <?php else: ?>
                        <video src="../assets/uploads/<?php echo $item['media_file']; ?>" class="w-full h-full object-cover opacity-80"></video>
                        <div class="absolute inset-0 flex items-center justify-center">
                            <i class="fas fa-play-circle text-4xl text-white drop-shadow-lg"></i>
                        </div>
                    <?php endif; ?>
                    <div class="absolute top-2 right-2 bg-black/70 text-white text-xs px-2 py-1 rounded">
                        <?php echo $item['cat_name']; ?>
                    </div>
                </div>
                
                <div class="p-5 flex flex-col flex-grow">
                    <h3 class="font-bold text-gray-800 text-lg mb-1 truncate"><?php echo $item['title']; ?></h3>
                    <p class="text-xs text-gray-400 mb-4">Added: <?php echo date('d M Y', strtotime($item['created_at'])); ?></p>
                    
                    <div class="mt-auto flex gap-2 pt-4 border-t border-gray-100">
                        <a href="edit_item.php?id=<?php echo $item['id']; ?>" class="flex-1 text-center bg-blue-50 text-blue-600 py-2 rounded text-sm font-medium hover:bg-blue-100 transition">
                            <i class="fas fa-edit"></i> Edit
                        </a>

                        <a href="delete_item.php?id=<?php echo $item['id']; ?>" class="flex-1 text-center bg-red-50 text-red-600 py-2 rounded text-sm font-medium hover:bg-red-100 transition" onclick="return confirm('Are you sure you want to delete this project permanently?');">
                            <i class="fas fa-trash-alt"></i> Delete
                        </a>
                    </div>
                </div>

            </div>
            <?php endforeach; ?>
        </div>

        <?php if(count($items) == 0): ?>
            <div class="text-center py-10 text-gray-500">
                <p>No projects uploaded yet.</p>
            </div>
        <?php endif; ?>

    </div>
</body>
</html>