<?php
// api/attendance_action.php
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';

header('Content-Type: application/json');

try {
    // Check Status
    if (isset($_GET['check_status'])) {
        $member_id = (int)$_GET['member_id'];
        $today = date('Y-m-d');
        
        $stmt = $pdo->prepare("SELECT id FROM attendance WHERE member_id = ? AND DATE(in_time) = ? AND out_time IS NULL ORDER BY id DESC LIMIT 1");
        $stmt->execute([$member_id, $today]);
        $record = $stmt->fetch();
        
        echo json_encode(['signed_in' => (bool)$record]);
        exit;
    }

// POST Action (Sign In / Out / Update)
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $type = $_POST['type'] ?? ''; 

        if ($type === 'update') {
            // Update Existing Record
            $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
            if (!$id) throw new Exception("Record ID missing");

            $newTime = $_POST['custom_time'] ?? '';
            $wasLate = isset($_POST['was_late']) ? (int)$_POST['was_late'] : 0;

            if (!strtotime($newTime)) throw new Exception("Invalid time format");

            $stmt = $pdo->prepare("UPDATE attendance SET in_time = ?, was_late = ? WHERE id = ?");
            $stmt->execute([$newTime, $wasLate, $id]);

            echo json_encode(['success' => true, 'message' => "Record updated"]);
            exit;
        }

        $member_id = isset($_POST['member_id']) ? (int)$_POST['member_id'] : 0;
        
        if (!$member_id) {
            throw new Exception("Member not specified");
        }
        
        // Determine Timestamp
        if (isset($_POST['custom_time']) && !empty($_POST['custom_time'])) {
            $now = $_POST['custom_time']; // Expects Y-m-d H:i:s
            // Validate format
            if (!strtotime($now)) {
                throw new Exception("Invalid date format provided");
            }
        } else {
            $now = date('Y-m-d H:i:s');
        }
        
        $target_date = date('Y-m-d', strtotime($now));

        if ($type === 'in') {
            // Late Logic
            $is_late = 0;
            $dayOfWeek = date('w', strtotime($now)); // 0 = Sunday
            $currentTime = date('H:i', strtotime($now));
            
            // Late Rules
            if ($dayOfWeek == 0 && $currentTime > '07:30') $is_late = 1;
            // Add other rules as needed or from config
            
            // Allow multiple sign-ins? Yes, but maybe warn if already open? 
            // For now, just insert.
            $stmt = $pdo->prepare("INSERT INTO attendance (member_id, in_time, was_late) VALUES (?, ?, ?)");
            $stmt->execute([$member_id, $now, $is_late]);
            
            echo json_encode(['success' => true, 'message' => "Signed In at " . date('g:i A', strtotime($now)) . ($is_late ? " (Late)" : "")]);

        } elseif ($type === 'out') {
            // Sign Out
            // Logic: Find an OPEN record for THIS DATE.
            // If custom time provided (backdating), look for record on that date.
            // If multiple, close the last one.
            
            $stmt = $pdo->prepare("SELECT id FROM attendance WHERE member_id = ? AND DATE(in_time) = ? AND out_time IS NULL ORDER BY id DESC LIMIT 1");
            $stmt->execute([$member_id, $target_date]);
            $record = $stmt->fetch();
            
            if ($record) {
                // Update existing open record
                $update = $pdo->prepare("UPDATE attendance SET out_time = ? WHERE id = ?");
                $update->execute([$now, $record['id']]);
                echo json_encode(['success' => true, 'message' => "Signed Out at " . date('g:i A', strtotime($now))]);
            } else {
                // No open record found for this date.
                // Output error as before
                echo json_encode(['success' => false, 'message' => "No open sign-in record found for " . $target_date]);
            }
        } else {
            throw new Exception("Invalid action type");
        }
    }
} catch (Exception $e) {
    http_response_code(500); 
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
