<?php
// Include database connection
require_once '../layouts/dbconn.php';
require_once '../layouts/session.php';

// Check if user is logged in and has appropriate permissions
$allowedRoles = [1, 3, 4]; // Admin, Broker, Agent
if (!in_array($_SESSION['role_id'], $allowedRoles)) {
    echo json_encode(['success' => false, 'message' => 'You do not have permission to perform this action.']);
    exit;
}

// Set content type to JSON
header('Content-Type: application/json');

// Check if required parameters are provided
if (!isset($_POST['user_id']) || !isset($_POST['password'])) {
    echo json_encode(['success' => false, 'message' => 'Missing required parameters.']);
    exit;
}

$userId = (int)$_POST['user_id'];
$password = $_POST['password'];
$notify = isset($_POST['notify']) ? (int)$_POST['notify'] : 0;

// Get agent ID if applicable
$agent_id = null;
if ($_SESSION['role_id'] == 3 || $_SESSION['role_id'] == 4) { // Broker or Agent
    $agentQuery = "SELECT id FROM brokers_agents WHERE user_id = {$_SESSION['user_id']}";
    $agentResult = $conn->query($agentQuery);
    if ($agentResult && $agentResult->num_rows > 0) {
        $agent_id = $agentResult->fetch_assoc()['id'];
    }
}

// Verify user exists and is a client
$clientQuery = "SELECT u.id, u.first_name, u.last_name, u.email, u.role_id FROM users u WHERE u.id = $userId";

// For brokers/agents, only allow resetting passwords for their clients
if ($agent_id) {
    $clientQuery .= " AND u.id IN (SELECT client_id FROM agent_clients WHERE agent_id = $agent_id)";
}

$clientResult = $conn->query($clientQuery);

if ($clientResult->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => 'Client not found or you do not have permission to reset this client\'s password.']);
    exit;
}

$client = $clientResult->fetch_assoc();

// Verify this is a client account
if ($client['role_id'] != 5) {
    echo json_encode(['success' => false, 'message' => 'You can only reset passwords for client accounts.']);
    exit;
}

// Begin transaction
$conn->begin_transaction();

try {
    // Hash the password
    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
    
    // Update password in the database
    $updateQuery = "UPDATE users SET password = '$hashedPassword' WHERE id = $userId";
    
    if ($conn->query($updateQuery)) {
        // Log the action
        $logQuery = "INSERT INTO activity_logs (user_id, activity_type, description, ip_address, related_to, related_id) 
                    VALUES ({$_SESSION['user_id']}, 'update', 'Reset password for client ID: $userId', '{$_SERVER['REMOTE_ADDR']}', 'client', $userId)";
        $conn->query($logQuery);
        
        // Send notification to client if requested
        if ($notify) {
            // Fetch email template
            $templateQuery = "SELECT * FROM notification_templates WHERE template_name = 'password_reset' AND template_type = 'email' LIMIT 1";
            $templateResult = $conn->query($templateQuery);
            
            if ($templateResult && $templateResult->num_rows > 0) {
                $template = $templateResult->fetch_assoc();
                
                // Fetch company name from settings
                $settingsQuery = "SELECT setting_value FROM settings WHERE setting_key = 'company_name'";
                $settingsResult = $conn->query($settingsQuery);
                $company_name = $settingsResult->fetch_assoc()['setting_value'];
                
                // Replace placeholders
                $subject = str_replace(
                    ['{{first_name}}', '{{last_name}}', '{{company_name}}'],
                    [$client['first_name'], $client['last_name'], $company_name],
                    $template['subject']
                );
                
                $message = str_replace(
                    ['{{first_name}}', '{{last_name}}', '{{company_name}}', '{{password}}'],
                    [$client['first_name'], $client['last_name'], $company_name, $password],
                    $template['body']
                );
                
                // Insert notification
                $notificationQuery = "INSERT INTO notifications (
                                        user_id, template_id, subject, message, 
                                        notification_type, related_to, related_id
                                    ) VALUES (
                                        $userId, {$template['id']}, '$subject', '$message', 
                                        'email', 'client', $userId
                                    )";
                $conn->query($notificationQuery);
                
                // Insert email log
                $emailQuery = "INSERT INTO email_logs (
                                notification_id, recipient_email, sender_email, 
                                subject, message, status
                            ) VALUES (
                                LAST_INSERT_ID(), '{$client['email']}', 'no-reply@example.com', 
                                '$subject', '$message', 'pending'
                            )";
                $conn->query($emailQuery);
            }
        }
        
        $conn->commit();
        
        echo json_encode([
            'success' => true, 
            'message' => 'Password reset successfully.' . ($notify ? ' A notification has been sent to the client.' : '')
        ]);
    } else {
        throw new Exception("Failed to update password: " . $conn->error);
    }
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>