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

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $id = $_POST['id'];
    $name = $conn->real_escape_string($_POST['upliner_name']);
    $status = $_POST['status'];

    // We keep the folder logic consistent
    $folder_name = preg_replace('/[^A-Za-z0-9_\-]/', '_', $name);
    $target_dir = "uploads/upliner_data/" . $folder_name . "/";
    if (!is_dir($target_dir)) mkdir($target_dir, 0777, true);

    $update_fields = ["upliner_name = '$name'", "status = '$status'"];

    for ($i = 1; $i <= 3; $i++) {
        if (!empty($_FILES["photo_$i"]["name"])) {
            $file_name = "photo_$i" . "_" . time() . "_" . basename($_FILES["photo_$i"]["name"]);
            $path = $target_dir . $file_name;
            
            if (move_uploaded_file($_FILES["photo_$i"]["tmp_name"], $path)) {
                $clean_path = str_replace("../", "", $path);
                $update_fields[] = "photo_$i = '$clean_path'";
            }
        }
    }

    $sql = "UPDATE upliners SET " . implode(', ', $update_fields) . " WHERE id = '$id'";

    if ($conn->query($sql) === TRUE) {
        $_SESSION['msg'] = "Upliner profile updated Successfully!";
        $_SESSION['msg_type'] = "success";
    } else {
        $_SESSION['msg'] = "Update failed: " . $conn->error;
        $_SESSION['msg_type'] = "error";
    }

    header("Location: ../manage-upliner.php");
    exit();
}