<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

// Only super admin (role 1) can do this
$user = requireRole([1]);
$db   = getDB();

if (post('action') !== 'confirm_reset') {
    apiError('Invalid action.', 400);
}

$confirm = post('confirm_text', '');
if ($confirm !== 'DELETE ALL DATA') {
    apiError('Confirmation text does not match.', 422);
}

try {
    $db->beginTransaction();
    $db->exec('SET FOREIGN_KEY_CHECKS = 0');

    $truncate = [
        'calendar_events',
        'checklist_instance_items',
        'checklist_instances',
        'job_card_checklist',
        'client_addresses',
        'client_asset_images',
        'client_assets',
        'client_contacts',
        'client_email_accounts',
        'client_files',
        'client_notes',
        'client_passwords',
        'clients',
        'employee_allowances',
        'employee_deductions',
        'employee_documents',
        'employee_files',
        'employee_leave',
        'employee_leave_balance',
        'employee_salaries',
        'employee_warnings',
        'employees',
        'fleet_costs',
        'fleet_documents',
        'fleet_service_schedule',
        'fleet_travel_log',
        'fleet_vehicles',
        'job_card_images',
        'job_card_locations',
        'job_card_notes',
        'job_card_planning',
        'job_card_reports',
        'job_card_technicians',
        'job_card_time_logs',
        'job_cards',
        'payroll_periods',
        'payroll_runs',
        'project_activity',
        'project_bugs',
        'project_files',
        'project_ftp',
        'project_members',
        'project_sections',
        'project_test_requests',
        'project_time_logs',
        'project_todos',
        'projects',
        'slips',
        'stock_inventory',
        'stock_items',
        'stock_transactions',
        'user_tokens',
    ];

    foreach ($truncate as $table) {
        $db->exec("TRUNCATE TABLE `{$table}`");
    }

    $db->exec('SET FOREIGN_KEY_CHECKS = 1');
    $db->commit();

    // Delete uploaded files (preserve directory structure & .htaccess)
    $uploadDirs = [
        __DIR__ . '/../../uploads/fleet/',
        __DIR__ . '/../../uploads/jobcards/',
        __DIR__ . '/../../uploads/slips/',
        __DIR__ . '/../../uploads/employees/',
    ];

    $deletedFiles = 0;
    foreach ($uploadDirs as $dir) {
        if (!is_dir($dir)) continue;
        $iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS)
        );
        foreach ($iterator as $file) {
            if ($file->isFile() && $file->getFilename() !== '.htaccess') {
                unlink($file->getRealPath());
                $deletedFiles++;
            }
        }
    }

    apiSuccess(
        ['deleted_files' => $deletedFiles],
        "Database cleared. {$deletedFiles} uploaded file(s) deleted."
    );

} catch (Exception $e) {
    if ($db->inTransaction()) {
        $db->rollBack();
        $db->exec('SET FOREIGN_KEY_CHECKS = 1');
    }
    apiError('Reset failed: ' . $e->getMessage(), 500);
}
