<?php
session_start();
require_once '../config/db.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $upliner_name = $_POST['upliner_name'];
    $uploaded_by = $_POST['uploaded_by'];
    $status = $_POST['status'];

    // 1. Create a clean folder name for the Upliner
    $unique_suffix = time() . "_" . rand(1000, 9999);
    $folder_name = preg_replace('/[^A-Za-z0-9_\-]/', '_', $upliner_name) . "_" . $unique_suffix;
    $base_dir = "../uploads/upliners_data/";
    $upliner_dir = $base_dir . $folder_name . "/";

    if (!is_dir($upliner_dir)) {
        mkdir($upliner_dir, 0777, true);
    }

    // 2. Helper function to process and clean paths for each photo
    function processOptionalPhoto($file_input_name, $dir) {
        if (!empty($_FILES[$file_input_name]["name"])) {
            $file_name = $file_input_name . "_" . time() . "_" . basename($_FILES[$file_input_name]["name"]);
            $target_path = $dir . $file_name;
            if (move_uploaded_file($_FILES[$file_input_name]["tmp_name"], $target_path)) {
                // Remove '../' if it exists in the path
                return str_replace("../", "", $target_path);
            }
        }
        return null;
    }

    // 3. Process all three photos
    $path1 = processOptionalPhoto("photo_1", $upliner_dir);
    $path2 = processOptionalPhoto("photo_2", $upliner_dir);
    $path3 = processOptionalPhoto("photo_3", $upliner_dir);

    // 4. SQL Insert (The DB Trigger handles GVUXXXX code)
    $safe_name = $conn->real_escape_string($upliner_name);
    
    $sql = "INSERT INTO upliners (upliner_name, photo_1, photo_2, photo_3, uploaded_by, status) 
            VALUES ('$safe_name', '$path1', '$path2', '$path3', '$uploaded_by', '$status')";

    if ($conn->query($sql) === TRUE) {
        $_SESSION['msg'] = "Upliner '$upliner_name' registered successfully!";
        $_SESSION['msg_type'] = "success";
    } else {
        $_SESSION['msg'] = "Database Error: " . $conn->error;
        $_SESSION['msg_type'] = "error";
    }

    $conn->close();
    header("Location: ../add-upliners.php");
    exit();
}
?>