<?php
// Debug script for admission application image upload
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();
require_once 'config/database.php';

// Check if uploads directory exists and create if not
$upload_dir = __DIR__ . '/uploads/students/';
if (!is_dir($upload_dir)) {
    $result = mkdir($upload_dir, 0755, true);
    echo "Upload directory created: " . ($result ? 'SUCCESS' : 'FAILED') . "<br>";
} else {
    echo "Upload directory exists<br>";
}

echo "Upload directory writable: " . (is_writable($upload_dir) ? 'YES' : 'NO') . "<br>";
echo "Upload directory readable: " . (is_readable($upload_dir) ? 'YES' : 'NO') . "<br>";

// Check PHP settings
echo "<h3>PHP Settings:</h3>";
echo "upload_max_filesize: " . ini_get('upload_max_filesize') . "<br>";
echo "post_max_size: " . ini_get('post_max_size') . "<br>";
echo "max_execution_time: " . ini_get('max_execution_time') . "<br>";
echo "max_input_time: " . ini_get('max_input_time') . "<br>";
echo "memory_limit: " . ini_get('memory_limit') . "<br>";

// Check if image utils exist
if (file_exists(__DIR__ . '/includes/image_utils.php')) {
    require_once 'includes/image_utils.php';
    echo "<h3>Image Utils:</h3>";
    echo "validate_and_compress_image function exists: " . (function_exists('validate_and_compress_image') ? 'YES' : 'NO') . "<br>";
} else {
    echo "<h3>ERROR:</h3>";
    echo "includes/image_utils.php does not exist!<br>";
}

// Check database connection
try {
    $pdo = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "<h3>Database Connection:</h3>";
    echo "Connected successfully<br>";
    
    // Check if admission_applications table exists
    $stmt = $pdo->query("SHOW TABLES LIKE 'admission_applications'");
    if ($stmt->rowCount() == 0) {
        echo "<h3>ERROR:</h3>";
        echo "Table 'admission_applications' does not exist!<br>";
    } else {
        echo "Table 'admission_applications' exists<br>";
        
        // Check if photo_path column exists
        $columns = $pdo->query("DESCRIBE admission_applications");
        $has_photo_path = false;
        $column_info = [];
        while ($row = $columns->fetch()) {
            if ($row['Field'] == 'photo_path') {
                $has_photo_path = true;
            }
            $column_info[] = $row['Field'];
        }
        
        echo "Has photo_path column: " . ($has_photo_path ? 'YES' : 'NO') . "<br>";
        echo "All columns: " . implode(', ', $column_info) . "<br>";
    }
} catch (PDOException $e) {
    echo "<h3>Database Error:</h3>";
    echo "Connection failed: " . $e->getMessage() . "<br>";
}

echo "<h3>Form Processing Test:</h3>";
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    echo "Form submitted<br>";
    
    if (isset($_FILES['student_photo']) && $_FILES['student_photo']['error'] === UPLOAD_ERR_OK) {
        echo "File uploaded successfully<br>";
        echo "File name: " . $_FILES['student_photo']['name'] . "<br>";
        echo "File size: " . $_FILES['student_photo']['size'] . " bytes<br>";
        echo "File type: " . $_FILES['student_photo']['type'] . "<br>";
        echo "Temporary file: " . $_FILES['student_photo']['tmp_name'] . "<br>";
    } else {
        echo "No file uploaded or upload error<br>";
        if (isset($_FILES['student_photo'])) {
            echo "Upload error code: " . $_FILES['student_photo']['error'] . "<br>";
        }
    }
    
    if (isset($_POST['captured_photo_data'])) {
        echo "Captured photo data detected<br>";
        echo "Length: " . strlen($_POST['captured_photo_data']) . " characters<br>";
    }
    
    if (isset($_POST['compressed_photo_data'])) {
        echo "Compressed photo data detected<br>";
        echo "Length: " . strlen($_POST['compressed_photo_data']) . " characters<br>";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Upload Debug</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .form-group { margin: 15px 0; }
        label { display: block; margin-bottom: 5px; font-weight: bold; }
        input, select, textarea { padding: 8px; width: 300px; }
        button { padding: 10px 20px; background: #007cba; color: white; border: none; cursor: pointer; }
        button:hover { background: #005a87; }
    </style>
</head>
<body>
    <h2>Test Image Upload Form</h2>
    <form method="POST" enctype="multipart/form-data">
        <div class="form-group">
            <label>Test Name:</label>
            <input type="text" name="test_name" value="Debug Test">
        </div>
        <div class="form-group">
            <label>Upload Photo:</label>
            <input type="file" name="student_photo" accept="image/*">
        </div>
        <button type="submit">Submit Test Form</button>
    </form>
    
    <h3>Recent Applications with Images (if any):</h3>
    <?php
    if (isset($pdo)) {
        try {
            $stmt = $pdo->query("SELECT application_no, first_name, last_name, photo_path, created_at FROM admission_applications WHERE photo_path IS NOT NULL AND photo_path != '' ORDER BY created_at DESC LIMIT 5");
            $applications = $stmt->fetchAll();
            
            if (count($applications) > 0) {
                echo "<table border='1' cellpadding='5' cellspacing='0'>";
                echo "<tr><th>Application No</th><th>Name</th><th>Photo Path</th><th>Date</th><th>Preview</th></tr>";
                foreach ($applications as $app) {
                    echo "<tr>";
                    echo "<td>" . htmlspecialchars($app['application_no']) . "</td>";
                    echo "<td>" . htmlspecialchars($app['first_name']) . " " . htmlspecialchars($app['last_name']) . "</td>";
                    echo "<td>" . htmlspecialchars($app['photo_path']) . "</td>";
                    echo "<td>" . htmlspecialchars($app['created_at']) . "</td>";
                    echo "<td>";
                    if (!empty($app['photo_path'])) {
                        $full_path = $app['photo_path'];
                        if (substr($full_path, 0, 1) !== '/') {
                            $full_path = '/' . $full_path;
                        }
                        $full_path = '..' . $full_path;
                        if (file_exists(__DIR__ . $full_path)) {
                            echo "<img src='" . htmlspecialchars($full_path) . "' style='width: 50px; height: 50px; object-fit: cover;'>";
                        } else {
                            echo "File not found";
                        }
                    }
                    echo "</td>";
                    echo "</tr>";
                }
                echo "</table>";
            } else {
                echo "<p>No applications with images found.</p>";
            }
        } catch (Exception $e) {
            echo "<p>Error querying applications: " . $e->getMessage() . "</p>";
        }
    }
    ?>
</body>
</html>