<?php
// committee_get_registration.php
error_reporting(E_ALL);
ini_set('display_errors', 0); // Turn off display errors for JSON response
header('Content-Type: application/json');

require_once 'db.php';
require_once 'helpers.php';

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

// Check if user is logged in as committee
if (!isset($_SESSION['committee_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

// Get registration ID from request
$registration_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($registration_id <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid registration ID']);
    exit;
}

try {
    // Check database connection
    if (!isset($mysqli1) || $mysqli1->connect_error) {
        echo json_encode(['success' => false, 'message' => 'Database connection error']);
        exit;
    }
    
    // Fetch registration data
    $stmt = $mysqli1->prepare("
        SELECT 
            id,
            student_id,
            semester_id,
            start,
            end,
            payment_amount,
            payment_reference,
            is_paid,
            notes,
            created_at,
            updated_at
        FROM registrations 
        WHERE id = ? AND (deleted_at IS NULL OR deleted_at = '0000-00-00 00:00:00')
    ");
    
    if (!$stmt) {
        echo json_encode(['success' => false, 'message' => 'Database prepare error: ' . $mysqli1->error]);
        exit;
    }
    
    $stmt->bind_param("i", $registration_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'Registration not found']);
        exit;
    }
    
    $registration = $result->fetch_assoc();
    
    // Format dates for input fields (Y-m-d format)
    $registration['start'] = !empty($registration['start']) && $registration['start'] != '0000-00-00' ? date('Y-m-d', strtotime($registration['start'])) : '';
    $registration['end'] = !empty($registration['end']) && $registration['end'] != '0000-00-00' ? date('Y-m-d', strtotime($registration['end'])) : '';
    
    echo json_encode([
        'success' => true,
        'registration' => $registration
    ]);
    
} catch (Exception $e) {
    error_log("Error in committee_get_registration.php: " . $e->getMessage());
    echo json_encode([
        'success' => false, 
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>