<?php
// ========== ANTI CACHE - SOLUSI DATA HILANG ==========
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
// =====================================================

session_start();

if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    http_response_code(401);
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

// CRITICAL: DISABLE ALL CACHE
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-cache, no-store, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: -1');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('ETag: "' . time() . '"');

// PENTING: Include autobackup function
require_once 'autobackup.php';

$dataFile = 'data/transactions.json';
$remindersFile = 'data/reminders.json';

// Ensure data directory exists
if (!file_exists('data')) {
    @mkdir('data', 0777, true);
}

// Ensure files exist
if (!file_exists($dataFile)) {
    @file_put_contents($dataFile, json_encode([], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}
if (!file_exists($remindersFile)) {
    @file_put_contents($remindersFile, json_encode([], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}

$action = $_GET['action'] ?? $_POST['action'] ?? '';

switch ($action) {
    case 'load':
        clearstatcache();
        $trans_content = @file_get_contents($dataFile);
        $rem_content = @file_get_contents($remindersFile);

        $transactions = $trans_content ? json_decode($trans_content, true) : [];
        $reminders = $rem_content ? json_decode($rem_content, true) : [];

        if (!is_array($transactions)) $transactions = [];
        if (!is_array($reminders)) $reminders = [];

        echo json_encode([
            'transactions' => $transactions,
            'reminders' => $reminders,
            'timestamp' => microtime(true),
            'count' => ['transactions' => count($transactions), 'reminders' => count($reminders)]
        ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        break;

    case 'save_transactions':
        $input = file_get_contents('php://input');
        $data = json_decode($input, true);

        if (isset($data['transactions']) && is_array($data['transactions'])) {
            $json_output = json_encode($data['transactions'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
            $result = @file_put_contents($dataFile, $json_output, LOCK_EX);
            clearstatcache();

            if ($result !== false) {
                // PENTING: Buat backup setelah save
                createAutoBackup();

                $verify = @file_get_contents($dataFile);
                $verify_data = json_decode($verify, true);

                echo json_encode([
                    'success' => true,
                    'message' => 'Data saved successfully',
                    'count' => count($verify_data ?? []),
                    'timestamp' => microtime(true)
                ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
            } else {
                http_response_code(500);
                echo json_encode([
                    'success' => false,
                    'error' => 'Failed to write file',
                    'timestamp' => microtime(true)
                ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
            }
        } else {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'error' => 'Invalid data format',
                'timestamp' => microtime(true)
            ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        }
        break;

    case 'save_reminders':
        $input = file_get_contents('php://input');
        $data = json_decode($input, true);

        if (isset($data['reminders']) && is_array($data['reminders'])) {
            $json_output = json_encode($data['reminders'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
            $result = @file_put_contents($remindersFile, $json_output, LOCK_EX);
            clearstatcache();

            if ($result !== false) {
                // PENTING: Buat backup setelah save
                createAutoBackup();

                $verify = @file_get_contents($remindersFile);
                $verify_data = json_decode($verify, true);

                echo json_encode([
                    'success' => true,
                    'message' => 'Data saved successfully',
                    'count' => count($verify_data ?? []),
                    'timestamp' => microtime(true)
                ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
            } else {
                http_response_code(500);
                echo json_encode([
                    'success' => false,
                    'error' => 'Failed to write file',
                    'timestamp' => microtime(true)
                ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
            }
        } else {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'error' => 'Invalid data format',
                'timestamp' => microtime(true)
            ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        }
        break;

    case 'restore':
        if (isset($_FILES['backup'])) {
            require_once 'restore.php';
        } else {
            http_response_code(400);
            echo json_encode(['error' => 'No file uploaded']);
        }
        break;

    default:
        http_response_code(400);
        echo json_encode(['error' => 'Invalid action']);
}
?>
