<?php
session_start();

if(!isset($_SESSION['id'])){
    die(json_encode([
        "status" => "error",
        "message" => "Login required"
    ]));
}

include("../../../config/db.php");
include($_SERVER['DOCUMENT_ROOT']."/SEAT/modules/Notification/notification_helper.php");

header('Content-Type: application/json');

$user_id = (int)$_SESSION['id'];

$name  = trim($_POST['advisor_name'] ?? "");
$phone = trim($_POST['advisor_phone'] ?? "");
$desc  = trim($_POST['description'] ?? "");

/* ================= VALIDATION ================= */

/* empty check */
if(!$name || !$phone || !$desc){

    echo json_encode([
        "status" => "error",
        "message" => "All fields are required"
    ]);
    exit;
}

/* digits only */
if(!ctype_digit($phone)){

    echo json_encode([
        "status" => "error",
        "message" => "Phone must contain digits only"
    ]);
    exit;
}

/* malaysia format */
if(!preg_match('/^01\d{8,9}$/', $phone)){

    echo json_encode([
        "status" => "error",
        "message" => "Invalid Malaysia phone number"
    ]);
    exit;
}

/* ================= GET CURRENT DATA ================= */
$currentQ = mysqli_query($conn,"
    SELECT advisor_name, advisor_phone, description
    FROM organizers
    WHERE user_id = $user_id
    LIMIT 1
");

$current = mysqli_fetch_assoc($currentQ);

if(!$current){

    echo json_encode([
        "status" => "error",
        "message" => "Organizer profile not found"
    ]);
    exit;
}

/* ================= SAFE DATA ================= */
$name_safe  = mysqli_real_escape_string($conn, $name);
$phone_safe = mysqli_real_escape_string($conn, $phone);
$desc_safe  = mysqli_real_escape_string($conn, $desc);

/* ================= DUPLICATE CHECK ================= */
$check = mysqli_query($conn,"
    SELECT phone 
    FROM participants
    WHERE phone = '$phone_safe'

    UNION

    SELECT advisor_phone AS phone
    FROM organizers
    WHERE advisor_phone = '$phone_safe'
    AND user_id != $user_id
");

if(mysqli_num_rows($check) > 0){

    echo json_encode([
        "status" => "error",
        "message" => "Phone already exists in system"
    ]);
    exit;
}

/* ================= UPDATE ================= */
$update = mysqli_query($conn,"
    UPDATE organizers
    SET
        advisor_name  = '$name_safe',
        advisor_phone = '$phone_safe',
        description   = '$desc_safe'
    WHERE user_id = $user_id
");

if($update){

    /* ================= BUILD SMART MESSAGE ================= */
    $changed = [];

    if($current['advisor_name'] !== $name){
        $changed[] = "advisor name";
    }

    if($current['advisor_phone'] !== $phone){
        $changed[] = "advisor phone number";
    }

    if($current['description'] !== $desc){
        $changed[] = "description";
    }

    $message = "Organizer profile has been updated.";

    if(count($changed) == 1){

        $message = ucfirst($changed[0])." has been updated.";

    }else if(count($changed) == 2){

        $message = ucfirst($changed[0])." and ".$changed[1]." have been updated.";

    }else if(count($changed) >= 3){

        $message = "Advisor profile details have been updated.";

    }

    /* ================= SEND NOTIFICATION ================= */
    if(count($changed) > 0){

        notify(
            $conn,
            $user_id,
            "Profile Updated",
            $message,
            "profile"
        );

    }

    echo json_encode([
        "status" => "success",
        "message" => "Profile updated successfully"
    ]);

}else{

    echo json_encode([
        "status" => "error",
        "message" => "Update failed"
    ]);

}
?>