<?php
session_start();
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: index.php');
    exit;
}
require 'dbconn.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $category_id   = intval($_POST['category']);
    $picture_name  = trim($_POST['picture_name']);
    $picture_desc  = trim($_POST['picture_desc']);

    // Use your existing folder
    $uploadDir = 'Image_Gallary/';

    $picture_image_path = '';
    $thumb_image_path   = '';

    // Upload Picture Image
    if (isset($_FILES['picture_image']) && $_FILES['picture_image']['error'] === UPLOAD_ERR_OK) {
        $ext = strtolower(pathinfo($_FILES['picture_image']['name'], PATHINFO_EXTENSION));
        if (in_array($ext, ['jpg', 'jpeg'])) {
            $newFileName = 'pic_' . time() . '_' . rand(1000, 9999) . '.' . $ext;
            $picture_image_path = $uploadDir . $newFileName;
            move_uploaded_file($_FILES['picture_image']['tmp_name'], $picture_image_path);
        } else {
            die("Only JPG/JPEG files are allowed for Picture Image.");
        }
    }

    // Upload Thumb Image
    if (isset($_FILES['thumb_image']) && $_FILES['thumb_image']['error'] === UPLOAD_ERR_OK) {
        $ext2 = strtolower(pathinfo($_FILES['thumb_image']['name'], PATHINFO_EXTENSION));
        if (in_array($ext2, ['jpg', 'jpeg'])) {
            $newThumbName = 'thumb_' . time() . '_' . rand(1000, 9999) . '.' . $ext2;
            $thumb_image_path = $uploadDir . $newThumbName;
            move_uploaded_file($_FILES['thumb_image']['tmp_name'], $thumb_image_path);
        } else {
            die("Only JPG/JPEG files are allowed for Thumb Image.");
        }
    }

    // Insert into DB
    $stmt = $mysqli->prepare("INSERT INTO project_pictures (catagory_id, picture_name, picture_image, thumb_image, picture_desc) VALUES (?, ?, ?, ?, ?)");
    $stmt->bind_param("issss", $category_id, $picture_name, $picture_image_path, $thumb_image_path, $picture_desc);

    if ($stmt->execute()) {
        echo "<script>alert('Picture uploaded successfully.'); window.location.href='manage_pictures.php';</script>";
    } else {
        echo "Database insert failed: " . $stmt->error;
    }
} else {
    echo "Invalid request.";
}
