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

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 0); // Don't display errors on screen, but log them

// Check if user is logged in and has admin role
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    $_SESSION['error'] = 'আপনার এই কাজের অনুমতি নেই।';
    header('Location: ../login.php');
    exit();
}

// Get student ID from URL
$student_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($student_id <= 0) {
    $_SESSION['error'] = 'অবৈধ ছাত্র আইডি।';
    header('Location: list.php');
    exit();
}

// Set longer timeout for this operation
set_time_limit(60);

try {
    // Ensure we have a fresh connection
    if (!$pdo) {
        throw new Exception('Database connection failed');
    }
    
    // First, get student information to check if exists and get user_id
    $stmt = $pdo->prepare("SELECT id, user_id, first_name, last_name, photo FROM students WHERE id = ?");
    if (!$stmt) {
        throw new Exception('Failed to prepare student select statement');
    }
    
    $result = $stmt->execute([$student_id]);
    if (!$result) {
        throw new Exception('Failed to execute student select query');
    }
    
    $student = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$student) {
        $_SESSION['error'] = 'ছাত্র খুঁজে পাওয়া যায়নি।';
        header('Location: list.php');
        exit();
    }
    
    // Store student name for success message
    $student_name = $student['first_name'] . ' ' . $student['last_name'];
    
    // Start transaction with proper isolation
    $pdo->beginTransaction();
    
    try {
        // Delete student photo if exists
        if (!empty($student['photo'])) {
            $photo_path = '../uploads/students/' . $student['photo'];
            if (file_exists($photo_path)) {
                @unlink($photo_path);
            }
        }
        
        // Handle user account deletion if exists
        if (!empty($student['user_id'])) {
            $user_id_to_delete = $student['user_id'];
            
            // Set user_id to NULL first to avoid constraint violation
            $stmt = $pdo->prepare("UPDATE students SET user_id = NULL WHERE id = ?");
            if (!$stmt) {
                throw new Exception('Failed to prepare user_id update statement');
            }
            
            $result = $stmt->execute([$student_id]);
            if (!$result) {
                throw new Exception('Failed to update user_id to NULL');
            }
            
            // Now delete the user account
            $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
            if (!$stmt) {
                throw new Exception('Failed to prepare user delete statement');
            }
            
            $result = $stmt->execute([$user_id_to_delete]);
            if (!$result) {
                throw new Exception('Failed to delete user account');
            }
        }
        
        // Delete the student record (related records will be deleted automatically due to CASCADE)
        $stmt = $pdo->prepare("DELETE FROM students WHERE id = ?");
        if (!$stmt) {
            throw new Exception('Failed to prepare student delete statement');
        }
        
        $result = $stmt->execute([$student_id]);
        if (!$result) {
            throw new Exception('Failed to execute student delete query');
        }
        
        $affected_rows = $stmt->rowCount();
        
        if ($affected_rows > 0) {
            // Commit the transaction
            $pdo->commit();
            $_SESSION['success'] = 'ছাত্র "' . $student_name . '" সফলভাবে মুছে ফেলা হয়েছে।';
        } else {
            // No rows affected - student might have been deleted already
            $pdo->rollBack();
            $_SESSION['error'] = 'ছাত্র আগেই মুছে ফেলা হয়েছে বা কোন সমস্যা হয়েছে।';
        }
        
    } catch (Exception $inner_e) {
        // Rollback transaction on any inner exception
        $pdo->rollBack();
        throw $inner_e;
    }
    
} catch (Exception $e) {
    // Ensure transaction is rolled back
    if ($pdo && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    
    // Log the error for debugging
    error_log("Student delete error: " . $e->getMessage() . " - Student ID: " . $student_id);
    
    $_SESSION['error'] = 'ছাত্র মুছে ফেলতে ব্যর্থ: ' . $e->getMessage();
}

// Redirect back to list page
header('Location: list.php');
exit();
?>