<?php
require 'config/database.php';

echo "Testing database connection...\n";

try {
    // Check if attendance table exists
    $stmt = $pdo->query("SHOW TABLES LIKE 'attendance'");
    if($stmt->rowCount() > 0) {
        echo "✓ Attendance table exists\n";
        
        // Describe the table structure
        echo "\nTable structure:\n";
        $stmt2 = $pdo->query('DESCRIBE attendance');
        while($row = $stmt2->fetch()) {
            echo "- " . $row['Field'] . " (" . $row['Type'] . ")\n";
        }
        
        // Test inserting a sample record
        echo "\nTesting attendance insertion...\n";
        $test_stmt = $pdo->prepare("INSERT INTO attendance (student_id, class_id, date, status, remarks, marked_by) VALUES (?, ?, ?, ?, ?, ?)");
        $result = $test_stmt->execute([999999, 14, '2026-01-16', 'present', 'Test record', 1]);
        
        if($result) {
            $inserted_id = $pdo->lastInsertId();
            echo "✓ Test record inserted successfully. ID: $inserted_id\n";
            
            // Verify the insertion
            $verify_stmt = $pdo->prepare("SELECT * FROM attendance WHERE id = ?");
            $verify_stmt->execute([$inserted_id]);
            $record = $verify_stmt->fetch();
            
            if($record) {
                echo "✓ Record verified in database\n";
                print_r($record);
                
                // Clean up test record
                $cleanup_stmt = $pdo->prepare("DELETE FROM attendance WHERE id = ?");
                $cleanup_stmt->execute([$inserted_id]);
                echo "✓ Test record cleaned up\n";
            } else {
                echo "✗ Record not found after insertion\n";
            }
        } else {
            echo "✗ Failed to insert test record\n";
            print_r($test_stmt->errorInfo());
        }
    } else {
        echo "✗ Attendance table does not exist\n";
    }
} catch(Exception $e) {
    echo "✗ Error: " . $e->getMessage() . "\n";
}
?>