<?php
// api/instructor_api.php - API for instructor CRUD operations
require_once '../db.php';
require_once '../helpers.php';

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

function validateInt($input, $default = 0) {
    return isset($input) && ctype_digit((string)$input) ? (int)$input : $default;
}

function validateString($input, $default = '') {
    if (isset($input) && is_string($input)) {
        return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
    }
    return $default;
}

$action = $_POST['action'] ?? $_GET['action'] ?? '';

// Get instructor by ID
if ($action == 'get' && isset($_GET['id'])) {
    $id = validateInt($_GET['id']);
    $query = "SELECT i.*, u.email, u.username 
              FROM instructors i 
              JOIN users u ON i.user_id = u.id 
              WHERE i.id = ?";
    $stmt = $mysqli1->prepare($query);
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($row = $result->fetch_assoc()) {
        echo json_encode([
            'success' => true,
            'instructor' => [
                'id' => $row['id'],
                'name' => $row['name'],
                'email' => $row['email'],
                'phone' => $row['phone'],
                'specialization' => $row['specialization'],
                'college_id' => $row['college_id']
            ]
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'المدرس غير موجود']);
    }
    exit;
}

// Add instructor
if ($action == 'add') {
    $name = validateString($_POST['name']);
    $email = validateString($_POST['email']);
    $phone = validateString($_POST['phone']);
    $specialization = validateString($_POST['specialization']);
    $college_id = validateInt($_POST['college_id']);
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $username = strtolower(str_replace(' ', '_', $name)) . rand(100, 999);
    
    // Start transaction
    $mysqli1->begin_transaction();
    
    try {
        // Create user account
        $user_query = "INSERT INTO users (username, email, password, role, created_at) VALUES (?, ?, ?, 'instructor', NOW())";
        $user_stmt = $mysqli1->prepare($user_query);
        $user_stmt->bind_param("sss", $username, $email, $password);
        $user_stmt->execute();
        $user_id = $mysqli1->insert_id;
        
        // Create instructor record
        $instructor_query = "INSERT INTO instructors (user_id, name, phone, specialization, college_id, created_at) 
                            VALUES (?, ?, ?, ?, ?, NOW())";
        $instructor_stmt = $mysqli1->prepare($instructor_query);
        $instructor_stmt->bind_param("issii", $user_id, $name, $phone, $specialization, $college_id);
        $instructor_stmt->execute();
        
        $mysqli1->commit();
        echo json_encode(['success' => true, 'message' => 'تم إضافة المدرس بنجاح']);
    } catch (Exception $e) {
        $mysqli1->rollback();
        echo json_encode(['success' => false, 'message' => 'حدث خطأ: ' . $e->getMessage()]);
    }
    exit;
}

// Update instructor
if ($action == 'update') {
    $id = validateInt($_POST['instructor_id']);
    $name = validateString($_POST['name']);
    $email = validateString($_POST['email']);
    $phone = validateString($_POST['phone']);
    $specialization = validateString($_POST['specialization']);
    $college_id = validateInt($_POST['college_id']);
    
    // Get user_id from instructor
    $user_query = "SELECT user_id FROM instructors WHERE id = ?";
    $user_stmt = $mysqli1->prepare($user_query);
    $user_stmt->bind_param("i", $id);
    $user_stmt->execute();
    $user_result = $user_stmt->get_result();
    $user_row = $user_result->fetch_assoc();
    $user_id = $user_row['user_id'];
    
    // Update instructor
    $instructor_query = "UPDATE instructors SET name = ?, phone = ?, specialization = ?, college_id = ? WHERE id = ?";
    $instructor_stmt = $mysqli1->prepare($instructor_query);
    $instructor_stmt->bind_param("sssii", $name, $phone, $specialization, $college_id, $id);
    $instructor_stmt->execute();
    
    // Update user email
    $user_update = "UPDATE users SET email = ? WHERE id = ?";
    $user_update_stmt = $mysqli1->prepare($user_update);
    $user_update_stmt->bind_param("si", $email, $user_id);
    $user_update_stmt->execute();
    
    // Update password if provided
    if (!empty($_POST['password'])) {
        $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
        $pass_update = "UPDATE users SET password = ? WHERE id = ?";
        $pass_stmt = $mysqli1->prepare($pass_update);
        $pass_stmt->bind_param("si", $password, $user_id);
        $pass_stmt->execute();
    }
    
    echo json_encode(['success' => true, 'message' => 'تم تحديث بيانات المدرس']);
    exit;
}

// Delete instructor
if ($action == 'delete') {
    $id = validateInt($_POST['id']);
    
    // Get user_id
    $user_query = "SELECT user_id FROM instructors WHERE id = ?";
    $user_stmt = $mysqli1->prepare($user_query);
    $user_stmt->bind_param("i", $id);
    $user_stmt->execute();
    $user_result = $user_stmt->get_result();
    $user_row = $user_result->fetch_assoc();
    $user_id = $user_row['user_id'];
    
    // Soft delete instructor
    $del_instructor = "UPDATE instructors SET deleted_at = NOW() WHERE id = ?";
    $del_stmt = $mysqli1->prepare($del_instructor);
    $del_stmt->bind_param("i", $id);
    $del_stmt->execute();
    
    // Soft delete user
    $del_user = "UPDATE users SET deleted_at = NOW() WHERE id = ?";
    $del_user_stmt = $mysqli1->prepare($del_user);
    $del_user_stmt->bind_param("i", $user_id);
    $del_user_stmt->execute();
    
    echo json_encode(['success' => true, 'message' => 'تم حذف المدرس']);
    exit;
}

// Assign subjects to instructor
if ($action == 'assign_subjects') {
    $instructor_id = validateInt($_POST['instructor_id']);
    $subjects = json_decode($_POST['subjects'], true);
    
    $success = true;
    foreach ($subjects as $subjectcode) {
        $check_query = "SELECT id FROM instructor_subjects WHERE instructor_id = ? AND subjectcode = ?";
        $check_stmt = $mysqli1->prepare($check_query);
        $check_stmt->bind_param("is", $instructor_id, $subjectcode);
        $check_stmt->execute();
        $check_result = $check_stmt->get_result();
        
        if ($check_result->num_rows == 0) {
            $insert_query = "INSERT INTO instructor_subjects (instructor_id, subjectcode, created_at) VALUES (?, ?, NOW())";
            $insert_stmt = $mysqli1->prepare($insert_query);
            $insert_stmt->bind_param("is", $instructor_id, $subjectcode);
            if (!$insert_stmt->execute()) {
                $success = false;
            }
            $insert_stmt->close();
        }
        $check_stmt->close();
    }
    
    echo json_encode(['success' => $success]);
    exit;
}

// Remove subject from instructor
if ($action == 'remove_subject') {
    $instructor_id = validateInt($_POST['instructor_id']);
    $subjectcode = validateString($_POST['subjectcode']);
    
    $delete_query = "DELETE FROM instructor_subjects WHERE instructor_id = ? AND subjectcode = ?";
    $delete_stmt = $mysqli1->prepare($delete_query);
    $delete_stmt->bind_param("is", $instructor_id, $subjectcode);
    $delete_stmt->execute();
    
    echo json_encode(['success' => true]);
    exit;
}

echo json_encode(['success' => false, 'message' => 'إجراء غير معروف']);
?>