<?php
require_once __DIR__ . '/../includes/db.php';

// Mock session setup for test
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
$_SESSION['company_id'] = 1;
$_SESSION['user_id'] = 1;
$company_id = $_SESSION['company_id'];

echo "========================================\n";
echo "Shifts Minimum Working Hours Test Suite\n";
echo "========================================\n";

try {
    // 1. Confirm column exists
    $hasCol = fetch("SHOW COLUMNS FROM shifts LIKE 'minimum_working_hours'");
    if ($hasCol) {
        echo "[PASS] 'minimum_working_hours' column exists in shifts table.\n";
    } else {
        throw new Exception("'minimum_working_hours' column DOES NOT exist.");
    }

    // 2. Perform mock Insert with minimum working hours
    $testShiftName = "Test Min Hours Shift " . uniqid();
    $startTime = "08:00:00";
    $endTime = "17:00:00";
    $workingHours = 9.00;
    $minWorkingHours = 7.50;

    query("
        INSERT INTO shifts (company_id, name, start_time, end_time, working_hours, minimum_working_hours) 
        VALUES (?, ?, ?, ?, ?, ?)
    ", [$company_id, $testShiftName, $startTime, $endTime, $workingHours, $minWorkingHours]);

    $inserted = fetch("SELECT * FROM shifts WHERE name = ? AND company_id = ?", [$testShiftName, $company_id]);
    if ($inserted && floatval($inserted['minimum_working_hours']) == 7.50) {
        echo "[PASS] Insert operation stored minimum_working_hours correctly.\n";
    } else {
        throw new Exception("Insert failed or minimum_working_hours value is incorrect: " . json_encode($inserted));
    }

    // 3. Perform mock Update with a new minimum working hours
    $newMinWorkingHours = 6.00;
    query("
        UPDATE shifts 
        SET minimum_working_hours = ? 
        WHERE id = ? AND company_id = ?
    ", [$newMinWorkingHours, $inserted['id'], $company_id]);

    $updated = fetch("SELECT * FROM shifts WHERE id = ?", [$inserted['id']]);
    if ($updated && floatval($updated['minimum_working_hours']) == 6.00) {
        echo "[PASS] Update operation modified minimum_working_hours correctly.\n";
    } else {
        throw new Exception("Update failed or minimum_working_hours value is incorrect.");
    }

    // 4. Clean up test record
    query("DELETE FROM shifts WHERE id = ?", [$inserted['id']]);
    echo "[PASS] Cleanup complete. Test record removed.\n";

    echo "========================================\n";
    echo "ALL TESTS PASSED SUCCESSFULLY!\n";
    echo "========================================\n";

} catch (Exception $e) {
    echo "[FAIL] Test failed: " . $e->getMessage() . "\n";
    exit(1);
}
