<?php
header("Content-Type: application/json");
require "../config/db.php";

// 1. Capture Form Data
// target_url now contains: uploads/templates/Category_Name/SubCategory_Name/
$target_url = $_POST['target_url']; 
$start_date = $_POST['start_date'];
$end_date   = $_POST['end_date'];
$status     = $_POST['status'];

// 2. Validation
if (empty($target_url)) {
    echo json_encode(["success" => false, "message" => "Please select both Category and Sub-category."]);
    exit;
}

if (strtotime($end_date) < strtotime($start_date)) {
    echo json_encode(["success" => false, "message" => "End date cannot be earlier than start date."]);
    exit;
}

// 3. Handle Banner Image Upload
$image_db_path = "";
if (!empty($_FILES["banner_image"]["name"])) {
    $upload_dir = "../uploads/banners/";
    
    // Create directory if it doesn't exist
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }

    $file_ext = pathinfo($_FILES["banner_image"]["name"], PATHINFO_EXTENSION);
    $file_name = "banner_" . time() . "_" . bin2hex(random_bytes(4)) . "." . $file_ext;
    $full_upload_path = $upload_dir . $file_name;
    
    if (move_uploaded_file($_FILES["banner_image"]["tmp_name"], $full_upload_path)) {
        // Path stored in DB for easy front-end access
        $image_db_path = "uploads/banners/" . $file_name;
    } else {
        echo json_encode(["success" => false, "message" => "Failed to upload image to server."]);
        exit;
    }
} else {
    echo json_encode(["success" => false, "message" => "Banner image is required."]);
    exit;
}

// 4. Insert into Database
$sql = "INSERT INTO banners (target_url, banner_image, status, start_date, end_date) 
        VALUES (?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sssss", $target_url, $image_db_path, $status, $start_date, $end_date);

if ($stmt->execute()) {
    echo json_encode([
        "success" => true, 
        "message" => "Banner BNR" . str_pad($conn->insert_id, 3, '0', STR_PAD_LEFT) . " created and targeted to " . $target_url
    ]);
} else {
    echo json_encode(["success" => false, "message" => "Database error: " . $conn->error]);
}

$stmt->close();
$conn->close();