<?php
// update_specialization.php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();

require 'db.php';
require 'helpers.php';
require_committee();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: manage-specializations.php');
    exit;
}

// Get and validate input
$specialization_id = isset($_POST['specialization_id']) ? (int)$_POST['specialization_id'] : 0;
$college_id = isset($_POST['college_id']) ? (int)$_POST['college_id'] : 0;
$section_id = isset($_POST['section_id']) ? (int)$_POST['section_id'] : 0;
$program_id = isset($_POST['program_id']) ? (int)$_POST['program_id'] : 0;
$specialization_name_ar = trim($_POST['specialization_name_ar'] ?? '');
$specialization_name_en = trim($_POST['specialization_name_en'] ?? '');
$degree_awarded_ar = trim($_POST['degree_awarded_ar'] ?? '');
$degree_awarded_en = trim($_POST['degree_awarded_en'] ?? '');

// Validate required fields
$errors = [];
if (!$specialization_id) $errors[] = 'معرف التخصص غير صالح';
if (!$college_id) $errors[] = 'الكلية مطلوبة';
if (!$section_id) $errors[] = 'القسم مطلوب';
if (!$program_id) $errors[] = 'البرنامج مطلوب';
if (empty($specialization_name_ar)) $errors[] = 'اسم التخصص بالعربية مطلوب';
if (empty($specialization_name_en)) $errors[] = 'اسم التخصص بالإنجليزية مطلوب';

// Check committee permissions
$committeeId = (int)($_SESSION['committee_id'] ?? 0);
$canAll = (bool)($_SESSION['committee_can_all'] ?? false);
$scopeCollege = isset($_SESSION['committee_college_id']) ? (int)$_SESSION['committee_college_id'] : null;

if (!$canAll && $scopeCollege !== null && $scopeCollege != $college_id) {
    $errors[] = 'لا تملك صلاحية تعديل تخصص لهذه الكلية';
}

if (!empty($errors)) {
    $_SESSION['error_message'] = implode(' - ', $errors);
    header('Location: manage-specializations.php');
    exit;
}

// Update specialization
$update_stmt = $mysqli1->prepare("
    UPDATE specializations 
    SET college_id = ?, section_id = ?, program_id = ?,
        specialization_name_ar = ?, specialization_name_en = ?,
        degree_awarded_ar = ?, degree_awarded_en = ?,
        updated_at = NOW()
    WHERE specialization_id = ? AND deleted_at IS NULL
");

$update_stmt->bind_param(
    "iiissssi",
    $college_id, $section_id, $program_id,
    $specialization_name_ar, $specialization_name_en,
    $degree_awarded_ar, $degree_awarded_en,
    $specialization_id
);

if ($update_stmt->execute()) {
    if ($update_stmt->affected_rows > 0) {
        $_SESSION['success_message'] = 'تم تحديث التخصص بنجاح';
    } else {
        $_SESSION['error_message'] = 'لم يتم العثور على التخصص أو لم يتم إجراء أي تغيير';
    }
} else {
    $_SESSION['error_message'] = 'حدث خطأ أثناء تحديث التخصص: ' . $mysqli1->error;
}

header('Location: manage-specializations.php');
exit;