<?php
// ─── Profile API ─────────────────────────────────────────────────────────────

function get() {
    $uid = require_login();
    global $conn;
    
    $result = mysqli_query($conn, "SELECT id, name, email, phone, status, role FROM h_user WHERE id='$uid'");
    $row = $result ? mysqli_fetch_assoc($result) : null;
    if (!$row) error_response('User not found', 404);

    $parts = explode(' ', $row['name']);
    success_response([
        'id' => $row['id'],
        'fname' => $parts[0],
        'lname' => $parts[1] ?? '',
        'email' => $row['email'],
        'phone' => $row['phone'],
        'status' => $row['status'],
        'role' => $row['role'] ?? 'user'
    ]);
}

function update() {
    $uid = require_login();
    global $conn;
    
    $email   = strtolower(trim($_POST['email'] ?? ''));
    $fname   = ucfirst(trim($_POST['fname'] ?? ''));
    $lname   = ucfirst(trim($_POST['lname'] ?? ''));
    $uname   = $fname . ' ' . $lname;
    $phone   = trim($_POST['phone'] ?? '');
    $opass   = trim($_POST['opass'] ?? '');

    $row = mysqli_fetch_assoc(mysqli_query($conn, "SELECT email, pass FROM h_user WHERE id='$uid'"));

    if (!check_password($opass, $row['pass'], $uid)) error_response('Current password is incorrect.');
    
    $unameSafe  = mysqli_real_escape_string($conn, $uname);
    $emailSafe  = mysqli_real_escape_string($conn, $email);
    $phoneSafe  = mysqli_real_escape_string($conn, $phone);
    $set = "name='$unameSafe', email='$emailSafe', phone='$phoneSafe'";
    
    if ($email !== $row['email']) {
        $rse = mysqli_query($conn, "SELECT id FROM h_user WHERE email='$emailSafe' AND id!='$uid'");
        if (mysqli_num_rows($rse) > 0) error_response('Email already in use.');
        $set .= ", status='0'";
    }
    
    mysqli_query($conn, "UPDATE h_user SET $set WHERE id='$uid'");
    success_response([], 'Profile updated.');
}

function password() {
    $uid = require_login();
    global $conn;
    
    $opass  = trim($_POST['opass'] ?? '');
    $pass1  = $_POST['pass1'] ?? '';
    $pass2  = $_POST['pass2'] ?? '';

    $row = mysqli_fetch_assoc(mysqli_query($conn, "SELECT pass FROM h_user WHERE id='$uid'"));
    if (!check_password($opass, $row['pass'], $uid)) error_response('Current password is incorrect.');
    if ($pass1 !== $pass2 || strlen($pass1) < 6) error_response('Passwords do not match or too short.');

    $passok = password_hash($pass2, PASSWORD_DEFAULT);
    mysqli_query($conn, "UPDATE h_user SET pass='$passok' WHERE id='$uid'");
    session_destroy();
    
    success_response([], 'Password changed. Please login again.');
}