<?php
/**
 * Sync Client API Endpoint
 * Handles syncing client data from offline storage
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

session_start();
require_once '../db_connect.php';

// Check authentication
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit;
}

$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role'] ?? 'user';

// Only brokers and admins can manage clients
if (!in_array($user_role, ['broker', 'admin'])) {
    echo json_encode(['success' => false, 'message' => 'Access denied']);
    exit;
}

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

if (!$input) {
    echo json_encode(['success' => false, 'message' => 'Invalid input']);
    exit;
}

try {
    // Check if this is an update or insert
    $server_id = isset($input['server_id']) ? intval($input['server_id']) : null;
    $local_id = $input['local_id'] ?? null;

    if ($server_id) {
        // Update existing client
        $stmt = $conn->prepare("
            UPDATE clients SET
                full_name = ?,
                email = ?,
                phone = ?,
                id_number = ?,
                address = ?,
                notes = ?,
                updated_at = NOW()
            WHERE id = ? AND broker_id = ?
        ");

        $stmt->bind_param(
            'ssssssii',
            $input['full_name'],
            $input['email'],
            $input['phone'],
            $input['id_number'],
            $input['address'],
            $input['notes'],
            $server_id,
            $user_id
        );

        if ($stmt->execute()) {
            echo json_encode([
                'success' => true,
                'message' => 'Client updated successfully',
                'server_id' => $server_id,
                'local_id' => $local_id
            ]);
        } else {
            throw new Exception('Failed to update client');
        }
    } else {
        // Insert new client
        $stmt = $conn->prepare("
            INSERT INTO clients (broker_id, full_name, email, phone, id_number, address, notes, created_at, updated_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
        ");

        $stmt->bind_param(
            'issssss',
            $user_id,
            $input['full_name'],
            $input['email'],
            $input['phone'],
            $input['id_number'],
            $input['address'],
            $input['notes']
        );

        if ($stmt->execute()) {
            $new_id = $conn->insert_id;

            // Log activity
            $action = 'create_client';
            $description = "Created client: " . $input['full_name'] . " (offline sync)";
            $ip = $_SERVER['REMOTE_ADDR'];

            $log_stmt = $conn->prepare("INSERT INTO activity_logs (user_id, action, description, ip_address) VALUES (?, ?, ?, ?)");
            $log_stmt->bind_param('isss', $user_id, $action, $description, $ip);
            $log_stmt->execute();

            echo json_encode([
                'success' => true,
                'message' => 'Client created successfully',
                'server_id' => $new_id,
                'local_id' => $local_id
            ]);
        } else {
            throw new Exception('Failed to create client');
        }
    }
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
