<?php
session_start();
require_once '../layouts/dbconn.php';

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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

// Verify user has permission to edit users
$current_user_id = $_SESSION['user_id'];
$current_user_role_sql = "SELECT ur.role_name, ur.role_id 
                          FROM users u 
                          JOIN user_roles ur ON u.role_id = ur.role_id 
                          WHERE u.user_id = ?";
$stmt = $conn->prepare($current_user_role_sql);
$stmt->bind_param("i", $current_user_id);
$stmt->execute();
$current_role_result = $stmt->get_result();
$current_user_role = $current_role_result->fetch_assoc();

$can_edit_users = false;
if ($current_user_role) {
    if ($current_user_role['role_name'] === 'Super Admin' || $current_user_role['role_name'] === 'Administrator') {
        $can_edit_users = true;
    } else {
        $perm_sql = "SELECT can_edit 
                     FROM role_permissions 
                     WHERE role_id = ? AND menu_id = (SELECT menu_id FROM menu_items WHERE menu_url = 'users.php' LIMIT 1)";
        $perm_stmt = $conn->prepare($perm_sql);
        $perm_stmt->bind_param("i", $current_user_role['role_id']);
        $perm_stmt->execute();
        $perm_result = $perm_stmt->get_result();
        $permissions = $perm_result->fetch_assoc();
        
        if ($permissions && $permissions['can_edit'] == 1) {
            $can_edit_users = true;
        }
    }
}

if (!$can_edit_users) {
    echo json_encode(['success' => false, 'message' => 'You do not have permission to edit users']);
    exit();
}

try {
    // Get and validate form data
    $user_id = isset($_POST['user_id']) ? (int)$_POST['user_id'] : 0;
    
    if (!$user_id) {
        throw new Exception('Invalid user ID');
    }
    
    // Verify user exists
    $check_sql = "SELECT user_id FROM users WHERE user_id = ?";
    $stmt = $conn->prepare($check_sql);
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    if ($stmt->get_result()->num_rows === 0) {
        throw new Exception('User not found');
    }
    
    // Sanitize and validate input
    $full_name = trim($_POST['full_name']);
    $email = trim($_POST['email']);
    $username = isset($_POST['username']) ? trim($_POST['username']) : null;
    $phone_primary = trim($_POST['phone_primary']);
    $phone_secondary = isset($_POST['phone_secondary']) ? trim($_POST['phone_secondary']) : null;
    $status = $_POST['status'];
    $role_id = (int)$_POST['role_id'];
    $branch_id = isset($_POST['branch_id']) && $_POST['branch_id'] ? (int)$_POST['branch_id'] : null;
    $supervisor_id = isset($_POST['supervisor_id']) && $_POST['supervisor_id'] ? (int)$_POST['supervisor_id'] : null;
    $hire_date = isset($_POST['hire_date']) && $_POST['hire_date'] ? $_POST['hire_date'] : null;
    $date_of_birth = isset($_POST['date_of_birth']) && $_POST['date_of_birth'] ? $_POST['date_of_birth'] : null;
    $gender = isset($_POST['gender']) && $_POST['gender'] ? $_POST['gender'] : null;
    $national_id = isset($_POST['national_id']) ? trim($_POST['national_id']) : null;
    $address = isset($_POST['address']) ? trim($_POST['address']) : null;
    $emergency_contact_name = isset($_POST['emergency_contact_name']) ? trim($_POST['emergency_contact_name']) : null;
    $emergency_contact_phone = isset($_POST['emergency_contact_phone']) ? trim($_POST['emergency_contact_phone']) : null;
    $license_number = isset($_POST['license_number']) ? trim($_POST['license_number']) : null;
    $license_expiry = isset($_POST['license_expiry']) && $_POST['license_expiry'] ? $_POST['license_expiry'] : null;
    
    // Validate required fields
    if (empty($full_name)) {
        throw new Exception('Full name is required');
    }
    
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        throw new Exception('Valid email address is required');
    }
    
    if (empty($phone_primary)) {
        throw new Exception('Primary phone is required');
    }
    
    if (!$role_id) {
        throw new Exception('Role is required');
    }
    
    if (!in_array($status, ['ACTIVE', 'INACTIVE', 'SUSPENDED', 'PENDING'])) {
        throw new Exception('Invalid status');
    }
    
    // Check if email is already used by another user
    $email_check_sql = "SELECT user_id FROM users WHERE email = ? AND user_id != ?";
    $stmt = $conn->prepare($email_check_sql);
    $stmt->bind_param("si", $email, $user_id);
    $stmt->execute();
    if ($stmt->get_result()->num_rows > 0) {
        throw new Exception('Email address is already in use by another user');
    }
    
    // Check if username is already used by another user (if provided)
    if ($username) {
        $username_check_sql = "SELECT user_id FROM users WHERE username = ? AND user_id != ?";
        $stmt = $conn->prepare($username_check_sql);
        $stmt->bind_param("si", $username, $user_id);
        $stmt->execute();
        if ($stmt->get_result()->num_rows > 0) {
            throw new Exception('Username is already in use by another user');
        }
    }
    
    // Handle profile picture upload
    $profile_picture = null;
    if (isset($_FILES['profile_picture']) && $_FILES['profile_picture']['error'] === UPLOAD_ERR_OK) {
        $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
        $max_size = 2 * 1024 * 1024; // 2MB
        
        if (!in_array($_FILES['profile_picture']['type'], $allowed_types)) {
            throw new Exception('Invalid image format. Only JPG, PNG, and GIF are allowed');
        }
        
        if ($_FILES['profile_picture']['size'] > $max_size) {
            throw new Exception('Image size must be less than 2MB');
        }
        
        // Create upload directory if it doesn't exist
        $upload_dir = '../uploads/profiles/';
        if (!file_exists($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }
        
        // Generate unique filename
        $file_extension = pathinfo($_FILES['profile_picture']['name'], PATHINFO_EXTENSION);
        $profile_picture = 'profile_' . $user_id . '_' . time() . '.' . $file_extension;
        $upload_path = $upload_dir . $profile_picture;
        
        if (!move_uploaded_file($_FILES['profile_picture']['tmp_name'], $upload_path)) {
            throw new Exception('Failed to upload profile picture');
        }
        
        // Delete old profile picture if exists
        $old_pic_sql = "SELECT profile_picture FROM users WHERE user_id = ?";
        $stmt = $conn->prepare($old_pic_sql);
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $old_pic_result = $stmt->get_result()->fetch_assoc();
        if ($old_pic_result && $old_pic_result['profile_picture']) {
            $old_pic_path = $upload_dir . $old_pic_result['profile_picture'];
            if (file_exists($old_pic_path)) {
                unlink($old_pic_path);
            }
        }
    }
    
    // Begin transaction
    $conn->begin_transaction();
    
    try {
        // Update user information
        $update_sql = "UPDATE users SET 
                        full_name = ?,
                        email = ?,
                        username = ?,
                        phone_primary = ?,
                        phone_secondary = ?,
                        status = ?,
                        role_id = ?,
                        branch_id = ?,
                        supervisor_id = ?,
                        hire_date = ?,
                        date_of_birth = ?,
                        gender = ?,
                        national_id = ?,
                        address = ?,
                        emergency_contact_name = ?,
                        emergency_contact_phone = ?,
                        license_number = ?,
                        license_expiry = ?";
        
        $params = [
            $full_name,
            $email,
            $username,
            $phone_primary,
            $phone_secondary,
            $status,
            $role_id,
            $branch_id,
            $supervisor_id,
            $hire_date,
            $date_of_birth,
            $gender,
            $national_id,
            $address,
            $emergency_contact_name,
            $emergency_contact_phone,
            $license_number,
            $license_expiry
        ];
        
        $types = "ssssssiiiissssssss";
        
        if ($profile_picture) {
            $update_sql .= ", profile_picture = ?";
            $params[] = $profile_picture;
            $types .= "s";
        }
        
        $update_sql .= ", updated_at = NOW() WHERE user_id = ?";
        $params[] = $user_id;
        $types .= "i";
        
        $stmt = $conn->prepare($update_sql);
        $stmt->bind_param($types, ...$params);
        
        if (!$stmt->execute()) {
            throw new Exception('Failed to update user information');
        }
        
        // Log the activity
        $log_sql = "INSERT INTO activity_logs (user_id, action, entity_type, entity_id, description, ip_address, user_agent) 
                    VALUES (?, 'UPDATE', 'user', ?, ?, ?, ?)";
        $log_stmt = $conn->prepare($log_sql);
        $description = "Updated user: " . $full_name;
        $ip_address = $_SERVER['REMOTE_ADDR'];
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        $log_stmt->bind_param("iisss", $current_user_id, $user_id, $description, $ip_address, $user_agent);
        $log_stmt->execute();
        
        // Commit transaction
        $conn->commit();
        
        echo json_encode([
            'success' => true,
            'message' => 'User updated successfully'
        ]);
        
    } catch (Exception $e) {
        $conn->rollback();
        
        // Delete uploaded image if transaction failed
        if ($profile_picture && file_exists($upload_dir . $profile_picture)) {
            unlink($upload_dir . $profile_picture);
        }
        
        throw $e;
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

$conn->close();
?>