<?php
// Attendance Saving Diagnostic Tool
require_once '../config/database.php';

echo "<!DOCTYPE html>
<html>
<head>
    <title>Attendance Saving Diagnostic</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .success { color: green; }
        .error { color: red; }
        .warning { color: orange; }
        .info { color: blue; }
        pre { background: #f5f5f5; padding: 10px; border-radius: 5px; }
    </style>
</head>
<body>
<h1>Attendance Saving Diagnostic Tool</h1>";

// Test 1: Database Connection
echo "<h2>1. Database Connection Test</h2>";
try {
    $pdo->query("SELECT 1");
    echo "<p class='success'>✓ Database connection successful</p>";
} catch (Exception $e) {
    echo "<p class='error'>✗ Database connection failed: " . $e->getMessage() . "</p>";
    exit;
}

// Test 2: Attendance Table Structure
echo "<h2>2. Attendance Table Check</h2>";
try {
    $stmt = $pdo->query("SHOW TABLES LIKE 'attendance'");
    if ($stmt->rowCount() > 0) {
        echo "<p class='success'>✓ Attendance table exists</p>";
        
        echo "<h3>Table Structure:</h3>";
        $stmt2 = $pdo->query("DESCRIBE attendance");
        echo "<table border='1' cellpadding='5'>";
        echo "<tr><th>Field</th><th>Type</th><th>Null</th><th>Key</th></tr>";
        while ($row = $stmt2->fetch()) {
            echo "<tr>";
            echo "<td>" . $row['Field'] . "</td>";
            echo "<td>" . $row['Type'] . "</td>";
            echo "<td>" . $row['Null'] . "</td>";
            echo "<td>" . $row['Key'] . "</td>";
            echo "</tr>";
        }
        echo "</table>";
    } else {
        echo "<p class='error'>✗ Attendance table does not exist</p>";
        exit;
    }
} catch (Exception $e) {
    echo "<p class='error'>✗ Error checking table: " . $e->getMessage() . "</p>";
}

// Test 3: Sample Data Insertion
echo "<h2>3. Sample Attendance Insertion Test</h2>";
try {
    // Use a test student ID that should exist
    $test_student_id = 1;
    $test_class_id = 14;
    $test_date = '2026-01-16';
    
    // Check if test student exists
    $student_check = $pdo->prepare("SELECT id, first_name, last_name FROM students WHERE id = ? AND status = 'active' LIMIT 1");
    $student_check->execute([$test_student_id]);
    $student = $student_check->fetch();
    
    if (!$student) {
        // Try to find any active student
        $student_check = $pdo->query("SELECT id, first_name, last_name FROM students WHERE status = 'active' LIMIT 1");
        $student = $student_check->fetch();
        if ($student) {
            $test_student_id = $student['id'];
            echo "<p class='info'>Using student ID: $test_student_id ({$student['first_name']} {$student['last_name']})</p>";
        } else {
            echo "<p class='error'>✗ No active students found in database</p>";
            exit;
        }
    } else {
        echo "<p class='info'>Using student ID: $test_student_id ({$student['first_name']} {$student['last_name']})</p>";
    }
    
    // Check if attendance already exists for this date
    $check_stmt = $pdo->prepare("SELECT id, status FROM attendance WHERE student_id = ? AND date = ?");
    $check_stmt->execute([$test_student_id, $test_date]);
    $existing = $check_stmt->fetch();
    
    if ($existing) {
        echo "<p class='warning'>⚠️ Attendance already exists for this student/date combination</p>";
        echo "<p>ID: {$existing['id']}, Status: {$existing['status']}</p>";
        
        // Option to clean up for testing
        if (isset($_GET['cleanup'])) {
            $delete_stmt = $pdo->prepare("DELETE FROM attendance WHERE id = ?");
            $delete_stmt->execute([$existing['id']]);
            echo "<p class='success'>✓ Previous record deleted for fresh test</p>";
            // Reload page without cleanup parameter
            echo "<script>setTimeout(function(){ window.location.href = '?'; }, 2000);</script>";
            exit;
        } else {
            echo "<p><a href='?cleanup=1'>Clean up existing record and retest</a></p>";
        }
    } else {
        echo "<p class='info'>📝 No existing attendance found, proceeding with insertion test...</p>";
        
        // Insert test attendance record
        $insert_stmt = $pdo->prepare("INSERT INTO attendance (student_id, class_id, date, status, remarks, marked_by) VALUES (?, ?, ?, ?, ?, ?)");
        $result = $insert_stmt->execute([$test_student_id, $test_class_id, $test_date, 'present', 'Diagnostic test', 1]);
        
        if ($result) {
            $inserted_id = $pdo->lastInsertId();
            echo "<p class='success'>✓ Attendance record inserted successfully!</p>";
            echo "<p>Inserted Record ID: $inserted_id</p>";
            
            // Verify the insertion
            $verify_stmt = $pdo->prepare("SELECT * FROM attendance WHERE id = ?");
            $verify_stmt->execute([$inserted_id]);
            $record = $verify_stmt->fetch();
            
            if ($record) {
                echo "<p class='success'>✓ Record verification successful!</p>";
                echo "<h3>Inserted Record Details:</h3>";
                echo "<pre>";
                print_r($record);
                echo "</pre>";
                
                // Clean up test record
                $cleanup_stmt = $pdo->prepare("DELETE FROM attendance WHERE id = ?");
                $cleanup_stmt->execute([$inserted_id]);
                echo "<p class='success'>✓ Test record cleaned up</p>";
                
            } else {
                echo "<p class='error'>✗ Record verification failed - inserted record not found</p>";
            }
        } else {
            echo "<p class='error'>✗ Failed to insert attendance record</p>";
            echo "<pre>";
            print_r($insert_stmt->errorInfo());
            echo "</pre>";
        }
    }
} catch (Exception $e) {
    echo "<p class='error'>✗ Error during insertion test: " . $e->getMessage() . "</p>";
}

// Test 4: AJAX Endpoint Simulation
echo "<h2>4. AJAX Endpoint Test</h2>";
echo "<p class='info'>Simulating the exact AJAX request that the auto-attendance system sends:</p>";

$ajax_test_data = [
    'action' => 'mark_attendance',
    'student_id' => $test_student_id,
    'class_id' => $test_class_id,
    'date' => $test_date
];

echo "<h3>Test Data:</h3>";
echo "<pre>";
print_r($ajax_test_data);
echo "</pre>";

// Simulate the exact processing logic
echo "<h3>Processing Simulation:</h3>";
try {
    $student_id = (int)$ajax_test_data['student_id'];
    $class_id = (int)$ajax_test_data['class_id'];
    $date = $ajax_test_data['date'];
    
    echo "<p>Validating data...</p>";
    
    // Check if student exists
    $student_check = $pdo->prepare("SELECT id, first_name, last_name FROM students WHERE id = ? AND status = 'active'");
    $student_check->execute([$student_id]);
    $student = $student_check->fetch();
    
    if ($student) {
        echo "<p class='success'>✓ Student validation passed: {$student['first_name']} {$student['last_name']}</p>";
        
        // Check existing attendance
        $check_stmt = $pdo->prepare("SELECT id FROM attendance WHERE student_id = ? AND date = ?");
        $check_stmt->execute([$student_id, $date]);
        $existing_attendance = $check_stmt->fetch();
        
        if (!$existing_attendance) {
            echo "<p>📝 No existing attendance, would insert new record...</p>";
            echo "<p class='success'>✓ Processing logic working correctly</p>";
        } else {
            echo "<p class='warning'>⚠️ Attendance already exists (this is normal)</p>";
        }
    } else {
        echo "<p class='error'>✗ Student validation failed</p>";
    }
} catch (Exception $e) {
    echo "<p class='error'>✗ Processing simulation failed: " . $e->getMessage() . "</p>";
}

echo "<h2>5. Recommendations</h2>";
echo "<ol>";
echo "<li>If database tests pass but auto-attendance fails, the issue is likely in the JavaScript/AJAX communication</li>";
echo "<li>Check browser console for JavaScript errors when using auto-attendance</li>";
echo "<li>Verify that session data is maintained during AJAX requests</li>";
echo "<li>Check if the POST request is reaching the server correctly</li>";
echo "<li>Review server error logs for any PHP errors during AJAX processing</li>";
echo "</ol>";

echo "<p><a href='../attendance_dashboard/auto_attendance.php?class_id=14&session=2024-25&date=2026-01-16'>← Back to Auto Attendance Page</a></p>";
echo "</body></html>";
?>