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

require_once 'config.php';

$conn = getDBConnection();

// Create auto_sync_status table if not exists
$sql = "CREATE TABLE IF NOT EXISTS auto_sync_status (
    id INT AUTO_INCREMENT PRIMARY KEY,
    phone_name VARCHAR(100) UNIQUE,
    auto_sync_enabled BOOLEAN DEFAULT FALSE,
    last_sync_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    sync_interval_seconds INT DEFAULT 30,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)";

if (!$conn->query($sql)) {
    http_response_code(500);
    echo json_encode(['error' => 'Failed to create auto_sync_status table']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // Get auto sync status for a phone
    $phoneName = $_GET['phone_name'] ?? '';
    
    if (empty($phoneName)) {
        http_response_code(400);
        echo json_encode(['error' => 'phone_name parameter is required']);
        exit;
    }
    
    $stmt = $conn->prepare("SELECT * FROM auto_sync_status WHERE phone_name = ?");
    $stmt->bind_param("s", $phoneName);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($row = $result->fetch_assoc()) {
        echo json_encode([
            'success' => true,
            'phone_name' => $row['phone_name'],
            'auto_sync_enabled' => (bool)$row['auto_sync_enabled'],
            'last_sync_time' => $row['last_sync_time'],
            'sync_interval_seconds' => $row['sync_interval_seconds']
        ]);
    } else {
        echo json_encode([
            'success' => true,
            'phone_name' => $phoneName,
            'auto_sync_enabled' => false,
            'last_sync_time' => null,
            'sync_interval_seconds' => 30
        ]);
    }
    
    $stmt->close();
    
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Update auto sync status for a phone
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);
    
    if (!$data || !isset($data['phone_name']) || !isset($data['auto_sync_enabled'])) {
        http_response_code(400);
        echo json_encode(['error' => 'phone_name and auto_sync_enabled are required']);
        exit;
    }
    
    $phoneName = $data['phone_name'];
    $autoSyncEnabled = $data['auto_sync_enabled'] ? 1 : 0;
    $syncInterval = $data['sync_interval_seconds'] ?? 30;
    
    // Insert or update the auto sync status
    $stmt = $conn->prepare("INSERT INTO auto_sync_status (phone_name, auto_sync_enabled, sync_interval_seconds) 
                           VALUES (?, ?, ?) 
                           ON DUPLICATE KEY UPDATE 
                           auto_sync_enabled = VALUES(auto_sync_enabled), 
                           sync_interval_seconds = VALUES(sync_interval_seconds),
                           last_sync_time = CURRENT_TIMESTAMP");
    
    $stmt->bind_param("sii", $phoneName, $autoSyncEnabled, $syncInterval);
    
    if ($stmt->execute()) {
        echo json_encode([
            'success' => true,
            'message' => 'Auto sync status updated successfully',
            'phone_name' => $phoneName,
            'auto_sync_enabled' => (bool)$autoSyncEnabled,
            'sync_interval_seconds' => $syncInterval
        ]);
    } else {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to update auto sync status']);
    }
    
    $stmt->close();
    
} else {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
}

$conn->close();
?>

