<?php
// Enable ALL error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('log_errors', 1);

// Start session
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once 'config.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: index.php');
    exit();
}

$pdo = getDB();
$message = '';
$student = null;
$students_without_photo = [];

// Handle search for student
if (isset($_POST['search']) && !empty($_POST['registration_no'])) {
    $registration_no = sanitize($_POST['registration_no']);
    try {
        $stmt = $pdo->prepare("SELECT * FROM certificates WHERE registration_no = ?");
        $stmt->execute([$registration_no]);
        $student = $stmt->fetch();
        
        if (!$student) {
            $message = '<div class="error">No student found with registration number: ' . htmlspecialchars($registration_no) . '</div>';
        }
    } catch(PDOException $e) {
        $message = '<div class="error">Database error: ' . $e->getMessage() . '</div>';
        error_log("Search error: " . $e->getMessage());
    }
}

// Handle photo update - FIXED: Check for file upload instead of button click
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['photo']) && $_FILES['photo']['error'] == 0 && isset($_POST['id'])) {
    try {
        $id = intval($_POST['id']);
        
        // Read file data (same as add_certificate.php)
        $photo_data = file_get_contents($_FILES['photo']['tmp_name']);
        if ($photo_data === false) {
            throw new Exception('Failed to read uploaded file.');
        }
        
        // Update database (same as add_certificate.php)
        $sql = "UPDATE certificates SET photo = ? WHERE id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$photo_data, $id]);
        
        logActivity($id, 'photo_mapped', $_SESSION['user_id']);
        $message = '<div class="success">✅ Photo mapped successfully! Size: ' . number_format(strlen($photo_data)) . ' bytes</div>';
        
        // Refresh student data
        $stmt = $pdo->prepare("SELECT * FROM certificates WHERE id = ?");
        $stmt->execute([$id]);
        $student = $stmt->fetch();
        
    } catch(PDOException $e) {
        $message = '<div class="error">Database Error: ' . $e->getMessage() . '</div>';
        error_log("Database error: " . $e->getMessage());
    } catch(Exception $e) {
        $message = '<div class="error">❌ Error: ' . $e->getMessage() . '</div>';
        error_log("General error: " . $e->getMessage());
    }
}

// Handle photo removal
if (isset($_POST['remove_photo']) && isset($_POST['id'])) {
    $id = intval($_POST['id']);
    try {
        $stmt = $pdo->prepare("UPDATE certificates SET photo = NULL WHERE id = ?");
        $stmt->execute([$id]);
        
        logActivity($id, 'photo_removed', $_SESSION['user_id']);
        $message = '<div class="success">Photo removed successfully!</div>';
        
        if ($student && $student['id'] == $id) {
            $stmt = $pdo->prepare("SELECT * FROM certificates WHERE id = ?");
            $stmt->execute([$id]);
            $student = $stmt->fetch();
        }
    } catch(Exception $e) {
        $message = '<div class="error">Error removing photo: ' . $e->getMessage() . '</div>';
        error_log("Photo removal error: " . $e->getMessage());
    }
}

// Get students without photos
if (isset($_GET['show_without_photo'])) {
    try {
        $stmt = $pdo->prepare("SELECT id, registration_no, name, degree FROM certificates WHERE photo IS NULL ORDER BY created_at DESC LIMIT 20");
        $stmt->execute();
        $students_without_photo = $stmt->fetchAll();
    } catch(PDOException $e) {
        error_log("Error fetching students without photo: " . $e->getMessage());
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Map Photo - SKUAST-K Portal</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #f5f7fb; }
        .sidebar { width: 250px; background: #2d3748; color: white; height: 100vh; position: fixed; padding: 20px 0; overflow-y: auto; }
        .sidebar h2 { padding: 0 20px 20px; border-bottom: 1px solid #4a5568; font-size: 18px; }
        .sidebar .user-info { padding: 20px; border-bottom: 1px solid #4a5568; margin-bottom: 20px; }
        .sidebar .user-info .name { font-weight: bold; font-size: 16px; }
        .sidebar .user-info .email { font-size: 12px; color: #a0aec0; }
        .sidebar a { display: block; padding: 12px 20px; color: #a0aec0; text-decoration: none; transition: all 0.3s; }
        .sidebar a:hover, .sidebar a.active { background: #4a5568; color: white; }
        .sidebar a i { width: 20px; margin-right: 10px; }
        .main-content { margin-left: 250px; padding: 30px; }
        .header { background: white; padding: 20px 30px; border-radius: 10px; margin-bottom: 30px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px; }
        .header h1 { font-size: 24px; color: #2d3748; }
        .search-section { background: white; padding: 30px; border-radius: 10px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); margin-bottom: 20px; }
        .student-card { background: white; padding: 30px; border-radius: 10px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); display: none; margin-top: 20px; }
        .student-card.show { display: flex; gap: 30px; flex-wrap: wrap; }
        .student-info { flex: 1; min-width: 300px; }
        .student-photo { flex: 0 0 220px; text-align: center; }
        .student-photo img { width: 200px; height: 200px; object-fit: cover; border-radius: 10px; border: 3px solid #e2e8f0; }
        .student-photo .no-photo { width: 200px; height: 200px; display: flex; align-items: center; justify-content: center; border: 2px dashed #e2e8f0; border-radius: 10px; color: #a0aec0; flex-direction: column; margin: 0 auto; background: #f7fafc; }
        .student-photo .no-photo i { font-size: 48px; margin-bottom: 10px; }
        .form-group { margin-bottom: 15px; }
        .form-group label { display: block; margin-bottom: 5px; color: #4a5568; font-weight: 500; }
        .form-group input[type="text"], 
        .form-group input[type="file"] { width: 100%; padding: 10px; border: 1px solid #e2e8f0; border-radius: 5px; font-size: 14px; }
        .form-group input[type="file"] { padding: 8px; background: #f7fafc; }
        .btn { background: #667eea; color: white; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer; font-size: 14px; transition: all 0.3s; text-decoration: none; display: inline-block; }
        .btn:hover { background: #5a67d8; }
        .btn-secondary { background: #718096; }
        .btn-secondary:hover { background: #4a5568; }
        .btn-success { background: #38a169; }
        .btn-success:hover { background: #2f855a; }
        .btn-danger { background: #e53e3e; }
        .btn-danger:hover { background: #c53030; }
        .btn-sm { padding: 5px 12px; font-size: 12px; }
        .error { background: #fee; color: #c33; padding: 12px; border-radius: 5px; margin-bottom: 20px; border-left: 4px solid #c33; }
        .success { background: #efe; color: #2d7d2d; padding: 12px; border-radius: 5px; margin-bottom: 20px; border-left: 4px solid #2d7d2d; }
        .student-detail { padding: 5px 0; color: #4a5568; }
        .student-detail strong { color: #2d3748; display: inline-block; width: 150px; }
        .list-section { background: white; padding: 30px; border-radius: 10px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); margin-top: 20px; }
        .list-section h3 { margin-bottom: 15px; color: #2d3748; }
        .list-section table { width: 100%; border-collapse: collapse; }
        .list-section th { text-align: left; padding: 10px; background: #f7fafc; color: #4a5568; font-weight: 600; border-bottom: 2px solid #e2e8f0; }
        .list-section td { padding: 10px; border-bottom: 1px solid #e2e8f0; }
        .list-section tr:hover { background: #f7fafc; }
        .search-box { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; }
        .search-box input[type="text"] { flex: 1; min-width: 200px; padding: 10px; border: 1px solid #e2e8f0; border-radius: 5px; font-size: 14px; }
        .photo-actions { margin-top: 15px; display: flex; gap: 10px; flex-wrap: wrap; justify-content: center; }
        .status-badge { padding: 4px 12px; border-radius: 20px; font-size: 12px; font-weight: 600; display: inline-block; }
        .status-draft { background: #fefcbf; color: #975a16; }
        .status-generated { background: #bee3f8; color: #2a69ac; }
        .status-issued { background: #c6f6d5; color: #22543d; }
        .preview-container { margin-top: 10px; display: none; }
        .preview-container.show { display: block; }
        .preview-container img { max-width: 200px; max-height: 200px; border-radius: 5px; border: 2px solid #e2e8f0; }
        .message-container { margin-bottom: 20px; }
        .photo-size { font-size: 12px; color: #718096; margin-top: 5px; }
        .debug-box { background: #f7fafc; padding: 15px; border-radius: 5px; border: 1px solid #e2e8f0; margin-top: 20px; font-family: monospace; font-size: 13px; }
        .debug-box h4 { margin-bottom: 10px; color: #2d3748; }
        .debug-box p { margin: 5px 0; color: #4a5568; }
        @media (max-width: 768px) {
            .sidebar { width: 200px; }
            .main-content { margin-left: 200px; padding: 15px; }
            .student-card.show { flex-direction: column; align-items: center; }
            .student-photo { flex: 0 0 auto; }
        }
        @media (max-width: 576px) {
            .sidebar { width: 100%; height: auto; position: relative; }
            .main-content { margin-left: 0; }
        }
    </style>
</head>
<body>
    <div class="sidebar">
        <h2>🎓 SKUAST-K Portal</h2>
        <div class="user-info">
            <div class="name"><?php echo htmlspecialchars($_SESSION['user_name'] ?? 'User'); ?></div>
            <div class="email"><?php echo htmlspecialchars($_SESSION['user_email'] ?? 'email'); ?></div>
        </div>
        <a href="dashboard.php"><i class="fas fa-tachometer-alt"></i> Dashboard</a>
        <a href="add_certificate.php"><i class="fas fa-plus-circle"></i> Add Certificate</a>
        <a href="bulk_upload.php"><i class="fas fa-upload"></i> Bulk Upload</a>
        <a href="map_photo.php" class="active"><i class="fas fa-image"></i> Map Photo</a>
        <a href="generate_certificate.php"><i class="fas fa-file-pdf"></i> Generate Certificate</a>
        <a href="view_certificates.php"><i class="fas fa-list"></i> View All</a>
        <a href="logout.php" style="margin-top: 30px; border-top: 1px solid #4a5568; padding-top: 20px;"><i class="fas fa-sign-out-alt"></i> Logout</a>
    </div>
    
    <div class="main-content">
        <div class="header">
            <h1>Map Student Photo</h1>
            <a href="dashboard.php" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Back</a>
        </div>
        
        <div class="message-container">
            <?php echo $message; ?>
        </div>
        
        <!-- Search Section -->
        <div class="search-section">
            <h3><i class="fas fa-search"></i> Search Student</h3>
            <form method="POST" action="" enctype="multipart/form-data">
                <div class="search-box">
                    <input type="text" name="registration_no" placeholder="Enter Registration Number (e.g., AG-2020-2283)" 
                           value="<?php echo isset($_POST['registration_no']) ? htmlspecialchars($_POST['registration_no']) : ''; ?>" required>
                    <button type="submit" name="search" class="btn"><i class="fas fa-search"></i> Search</button>
                    <a href="?show_without_photo=1" class="btn btn-secondary"><i class="fas fa-users"></i> Without Photo</a>
                </div>
            </form>
        </div>
        
        <!-- Student Card -->
        <?php if ($student): ?>
        <div class="student-card show" id="studentCard">
            <div class="student-photo">
                <?php if (!empty($student['photo'])): ?>
                    <img src="data:image/jpeg;base64,<?php echo base64_encode($student['photo']); ?>" alt="Student Photo" id="studentPhoto">
                    <div class="photo-size">📷 Photo size: <?php echo number_format(strlen($student['photo'])); ?> bytes</div>
                    <div class="photo-actions">
                        <form method="POST" action="" style="display:inline;">
                            <input type="hidden" name="id" value="<?php echo $student['id']; ?>">
                            <button type="submit" name="remove_photo" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure you want to remove this photo? This action cannot be undone.')">
                                <i class="fas fa-trash"></i> Remove Photo
                            </button>
                        </form>
                    </div>
                <?php else: ?>
                    <div class="no-photo">
                        <i class="fas fa-user-circle"></i>
                        <p style="margin-top: 10px;">No Photo Uploaded</p>
                        <p style="font-size: 12px; color: #999; margin-top: 5px;">Upload a photo below</p>
                    </div>
                <?php endif; ?>
            </div>
            <div class="student-info">
                <h3 style="color: #2d3748; margin-bottom: 10px;"><?php echo htmlspecialchars($student['name']); ?></h3>
                <div class="student-detail"><strong>Registration No:</strong> <?php echo htmlspecialchars($student['registration_no']); ?></div>
                <div class="student-detail"><strong>Father:</strong> <?php echo htmlspecialchars($student['father_name']); ?></div>
                <div class="student-detail"><strong>Mother:</strong> <?php echo htmlspecialchars($student['mother_name']); ?></div>
                <div class="student-detail"><strong>Degree:</strong> <?php echo htmlspecialchars($student['degree']); ?></div>
                <div class="student-detail"><strong>GPA:</strong> <?php echo $student['grade_point_average']; ?></div>
                <div class="student-detail"><strong>Certificate No:</strong> <?php echo htmlspecialchars($student['certificate_no']); ?></div>
                <div class="student-detail"><strong>ID:</strong> <?php echo $student['id']; ?></div>
                <div class="student-detail"><strong>Status:</strong> 
                    <span class="status-badge status-<?php echo $student['certificate_status']; ?>">
                        <?php echo ucfirst($student['certificate_status']); ?>
                    </span>
                </div>
                
                <!-- Photo Upload Form -->
                <form method="POST" action="" enctype="multipart/form-data" style="margin-top: 20px; padding-top: 20px; border-top: 1px solid #e2e8f0;" id="photoForm">
                    <input type="hidden" name="id" value="<?php echo $student['id']; ?>">
                    <div class="form-group">
                        <label for="photoUpload"><i class="fas fa-camera"></i> Upload New Photo</label>
                        <input type="file" name="photo" id="photoUpload" accept="image/*" onchange="previewImage(this)">
                        <small style="color: #718096; font-size: 12px; display: block; margin-top: 5px;">
                            Supported formats: JPEG, PNG, GIF, WebP. Max size: 5MB
                            <br>Current PHP upload limit: <?php echo ini_get('upload_max_filesize'); ?>
                        </small>
                    </div>
                    <div id="previewContainer" class="preview-container">
                        <p style="font-size: 12px; color: #718096; margin-bottom: 5px;">Preview:</p>
                        <img id="imagePreview" src="#" alt="Preview">
                    </div>
                    <button type="submit" name="submit" class="btn btn-success" id="uploadBtn">
                        <i class="fas fa-upload"></i> Map Photo
                    </button>
                </form>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- Students Without Photo List -->
        <?php if (!empty($students_without_photo)): ?>
        <div class="list-section">
            <h3><i class="fas fa-users"></i> Students Without Photo (Latest 20)</h3>
            <?php if (count($students_without_photo) > 0): ?>
                <table>
                    <thead>
                        <tr>
                            <th>Registration No</th>
                            <th>Name</th>
                            <th>Degree</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($students_without_photo as $s): ?>
                        <tr>
                            <td><strong><?php echo htmlspecialchars($s['registration_no']); ?></strong></td>
                            <td><?php echo htmlspecialchars($s['name']); ?></td>
                            <td><?php echo htmlspecialchars($s['degree']); ?></td>
                            <td>
                                <form method="POST" action="" style="display:inline;">
                                    <input type="hidden" name="registration_no" value="<?php echo htmlspecialchars($s['registration_no']); ?>">
                                    <button type="submit" name="search" class="btn btn-secondary btn-sm">
                                        <i class="fas fa-edit"></i> Map Photo
                                    </button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <p style="color: #718096; text-align: center; padding: 20px;">All students have photos!</p>
            <?php endif; ?>
        </div>
        <?php endif; ?>
        
        <!-- Debug Box -->
        
    </div>

    <script>
        function previewImage(input) {
            const preview = document.getElementById('imagePreview');
            const container = document.getElementById('previewContainer');
            
            if (input.files && input.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    preview.src = e.target.result;
                    container.classList.add('show');
                }
                reader.readAsDataURL(input.files[0]);
            } else {
                container.classList.remove('show');
            }
        }
        
        // Form validation
        document.getElementById('photoForm')?.addEventListener('submit', function(e) {
            const fileInput = document.getElementById('photoUpload');
            const btn = document.getElementById('uploadBtn');
            
            if (!fileInput.files || fileInput.files.length === 0) {
                e.preventDefault();
                alert('Please select a photo to upload.');
                return false;
            }
            
            const file = fileInput.files[0];
            if (file.size > 5 * 1024 * 1024) {
                e.preventDefault();
                alert('File size exceeds 5MB limit. Please compress your image.');
                return false;
            }
            
            // Show loading state
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Uploading...';
            btn.disabled = true;
        });
    </script>
</body>
</html>