<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include 'db_connect.php';

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

// استلام البيانات من الجافاسكريبت
$input = json_decode(file_get_contents('php://input'), true);
$student_id = $input['student_id'] ?? '';
$teacher_name = $input['teacher_name'] ?? '';
$date = $input['date'] ?? '';

if (empty($student_id) || empty($teacher_name) || empty($date)) {
    echo json_encode(['status' => 'error', 'message' => 'بيانات ناقصة']);
    exit;
}

// 1. تسجيل تاريخ الغياب في جدول attendance
$sql = "INSERT INTO attendance (student_id, teacher_name, attendance_date, status) VALUES (?, ?, ?, 'absent')";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sss", $student_id, $teacher_name, $date);

if ($stmt->execute()) {
    // 2. تحديث ذكي: زيادة عدد أيام الغياب (+1) في جدول students تلقائياً
    $update_sql = "UPDATE students SET absence_days = absence_days + 1 WHERE student_id = ? AND teacher_name = ?";
    $update_stmt = $conn->prepare($update_sql);
    $update_stmt->bind_param("ss", $student_id, $teacher_name);
    $update_stmt->execute();

    echo json_encode(['status' => 'success']);
} else {
    echo json_encode(['status' => 'error', 'message' => $conn->error]);
}
?>