<?php
session_start();
header('Content-Type: application/json');

// Include database connection
include '../layouts/dbconn.php';

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

// Check permissions
$user_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT HasPermission(?, 'users_edit') as has_permission");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$permission_result = $stmt->get_result()->fetch_assoc();

if (!$permission_result['has_permission']) {
    echo json_encode(['success' => false, 'message' => 'Insufficient permissions']);
    exit();
}

// Validate POST data
if (!isset($_POST['agent_id'])) {
    echo json_encode(['success' => false, 'message' => 'Missing agent ID']);
    exit();
}

$agent_id = (int)$_POST['agent_id'];

try {
    $conn->begin_transaction();
    
    // Get agent information
    $agent_sql = "SELECT u.full_name, u.email, u.agent_code, u.username 
                  FROM users u 
                  WHERE u.user_id = ? AND u.agent_code IS NOT NULL";
    $agent_stmt = $conn->prepare($agent_sql);
    $agent_stmt->bind_param("i", $agent_id);
    $agent_stmt->execute();
    $agent_info = $agent_stmt->get_result()->fetch_assoc();
    
    if (!$agent_info) {
        throw new Exception('Agent not found');
    }
    
    // Generate temporary password
    $temp_password = generateTemporaryPassword();
    $password_hash = password_hash($temp_password, PASSWORD_DEFAULT);
    
    // Generate password reset token
    $reset_token = bin2hex(random_bytes(32));
    $reset_expires = date('Y-m-d H:i:s', strtotime('+24 hours'));
    
    // Update user with new password and reset token
    $update_sql = "UPDATE users SET 
                   password_hash = ?, 
                   password_reset_token = ?, 
                   password_reset_expires = ?, 
                   login_attempts = 0,
                   updated_at = CURRENT_TIMESTAMP 
                   WHERE user_id = ?";
    $update_stmt = $conn->prepare($update_sql);
    $update_stmt->bind_param("sssi", $password_hash, $reset_token, $reset_expires, $agent_id);
    
    if (!$update_stmt->execute()) {
        throw new Exception('Failed to update password');
    }
    
    // Send password reset email
    $email_subject = "Password Reset - Ultrasure Insurance Platform";
    $email_message = "Dear {$agent_info['full_name']},\n\n";
    $email_message .= "Your password has been reset by an administrator.\n\n";
    $email_message .= "Your temporary login credentials:\n";
    $email_message .= "Username: {$agent_info['username']}\n";
    $email_message .= "Temporary Password: $temp_password\n\n";
    $email_message .= "Please log in and change your password immediately.\n";
    $email_message .= "This temporary password will expire in 24 hours.\n\n";
    $email_message .= "If you did not request this reset, please contact your supervisor immediately.\n\n";
    $email_message .= "Best regards,\n";
    $email_message .= "Ultrasure Insurance Platform";
    
    // Insert into communication log
    $comm_sql = "INSERT INTO communication_log (
        recipient_type, recipient_id, communication_type, subject, message, 
        recipient_contact, status, sent_by, created_at
    ) VALUES ('AGENT', ?, 'EMAIL', ?, ?, ?, 'PENDING', ?, CURRENT_TIMESTAMP)";
    
    $comm_stmt = $conn->prepare($comm_sql);
    $comm_stmt->bind_param("isssi", $agent_id, $email_subject, $email_message, 
                          $agent_info['email'], $user_id);
    $comm_stmt->execute();
    
    $communication_id = $conn->insert_id;
    
    // Log the activity
    $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, new_values, ip_address, user_agent) 
               VALUES (?, 'PASSWORD_RESET', 'AGENT', ?, 'USER', ?, ?, ?)";
    $log_stmt = $conn->prepare($log_sql);
    
    $log_data = json_encode([
        'agent_name' => $agent_info['full_name'],
        'agent_code' => $agent_info['agent_code'],
        'reset_by' => $_SESSION['full_name'],
        'reset_method' => 'admin_reset'
    ]);
    $ip_address = $_SERVER['REMOTE_ADDR'] ?? '';
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    
    $log_stmt->bind_param("iissss", $user_id, $agent_id, $log_data, $ip_address, $user_agent);
    $log_stmt->execute();
    
    // Mark email as sent (in a real implementation, you'd integrate with email service)
    $update_comm_sql = "UPDATE communication_log SET status = 'SENT', sent_at = CURRENT_TIMESTAMP WHERE log_id = ?";
    $update_comm_stmt = $conn->prepare($update_comm_sql);
    $update_comm_stmt->bind_param("i", $communication_id);
    $update_comm_stmt->execute();
    
    $conn->commit();
    
    echo json_encode([
        'success' => true, 
        'message' => 'Password reset successfully. Temporary password sent to agent.',
        'agent_name' => $agent_info['full_name'],
        'email_sent' => true
    ]);
    
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

/**
 * Generate a secure temporary password
 */
function generateTemporaryPassword($length = 12) {
    $uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $lowercase = 'abcdefghijklmnopqrstuvwxyz';
    $numbers = '0123456789';
    $symbols = '!@#$%^&*';
    
    $all_chars = $uppercase . $lowercase . $numbers . $symbols;
    
    $password = '';
    
    // Ensure at least one character from each set
    $password .= $uppercase[random_int(0, strlen($uppercase) - 1)];
    $password .= $lowercase[random_int(0, strlen($lowercase) - 1)];
    $password .= $numbers[random_int(0, strlen($numbers) - 1)];
    $password .= $symbols[random_int(0, strlen($symbols) - 1)];
    
    // Fill the rest of the password
    for ($i = 4; $i < $length; $i++) {
        $password .= $all_chars[random_int(0, strlen($all_chars) - 1)];
    }
    
    // Shuffle the password
    return str_shuffle($password);
}

$conn->close();
?>