<?php
// delete_registration.php - Handle deletion of student registration
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'db.php';
require 'helpers.php';

header('Content-Type: application/json');

// Check if user is logged in and has permission
session_start();
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'غير مصرح بالدخول']);
    exit;
}

// Check if required parameters are provided
$registration_id = isset($_POST['registration_id']) ? (int)$_POST['registration_id'] : 0;
$student_id = isset($_POST['student_id']) ? trim($_POST['student_id']) : '';

if (!$registration_id || empty($student_id)) {
    echo json_encode(['success' => false, 'message' => 'معرف التسجيل أو رقم الطالب غير صالح']);
    exit;
}

try {
    // Begin transaction
    $mysqli1->begin_transaction();
    
    // 1. First, check if registration exists and get details
    $check_stmt = $mysqli1->prepare("
        SELECT r.*, s.name as semester_name, s.code as semester_code
        FROM registrations r
        INNER JOIN semesters s ON r.semester_id = s.id
        WHERE r.id = ? AND r.student_id = ? AND r.deleted_at IS NULL
    ");
    $check_stmt->bind_param("is", $registration_id, $student_id);
    $check_stmt->execute();
    $registration = $check_stmt->get_result()->fetch_assoc();
    $check_stmt->close();
    
    if (!$registration) {
        throw new Exception('التسجيل غير موجود');
    }
    
    // 2. Soft delete the registration (set deleted_at timestamp)
    $delete_stmt = $mysqli1->prepare("
        UPDATE registrations 
        SET deleted_at = NOW(), updated_at = NOW() 
        WHERE id = ? AND student_id = ?
    ");
    $delete_stmt->bind_param("is", $registration_id, $student_id);
    $delete_stmt->execute();
    
    if ($delete_stmt->affected_rows === 0) {
        throw new Exception('فشل حذف التسجيل');
    }
    $delete_stmt->close();
    
    // 3. Log the deletion action
    $user_id = $_SESSION['user_id'];
    $user_name = $_SESSION['user_name'] ?? 'مستخدم غير معروف';
    $action = "تم حذف تسجيل الطالب {$student_id} من الفصل {$registration['semester_name']} ({$registration['semester_code']}) - الرقم المرجعي: {$registration['payment_reference']}";
    $ip_address = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
    
    $log_stmt = $mysqli1->prepare("
        INSERT INTO logs (user_id, action, ip_address, created_at) 
        VALUES (?, ?, ?, NOW())
    ");
    $log_stmt->bind_param("iss", $user_id, $action, $ip_address);
    $log_stmt->execute();
    $log_stmt->close();
    
    // 4. Also delete related records from registration_constraints if exists
    $check_constraints = $mysqli1->query("
        SHOW TABLES LIKE 'registration_constraints'
    ");
    
    if ($check_constraints->num_rows > 0) {
        $delete_constraints = $mysqli1->prepare("
            DELETE FROM registration_constraints 
            WHERE registration_id = ?
        ");
        $delete_constraints->bind_param("i", $registration_id);
        $delete_constraints->execute();
        $delete_constraints->close();
    }
    
    // Commit transaction
    $mysqli1->commit();
    
    echo json_encode([
        'success' => true,
        'message' => "تم حذف التسجيل بنجاح من الفصل الدراسي {$registration['semester_name']}"
    ]);
    
} catch (Exception $e) {
    // Rollback transaction on error
    $mysqli1->rollback();
    
    error_log("Delete Registration Error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'حدث خطأ أثناء حذف التسجيل: ' . $e->getMessage()
    ]);
}