<?php
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';

header('Content-Type: application/json; charset=utf-8');

// Auth check
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'غير مصرح']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'طريقة غير صحيحة']);
    exit;
}

$data     = json_decode($_POST['table_data'] ?? '[]', true);
$unit_id  = $_POST['selected_unit'] ?? null;
$sel_date = $_POST['selected_date'] ?? date('Y-m-d');

if (!$unit_id || empty($data)) {
    echo json_encode(['success' => false, 'message' => 'يرجى اختيار قسم وإدخال بيانات صحيحة']);
    exit;
}

try {
    $db  = new Database();
    $pdo = $db->getConnection();

    // حذف البيانات القديمة لنفس التاريخ والقسم
    $pdo->prepare("DELETE FROM patient_medication_tracking WHERE tracking_date = ? AND unit_id = ?")
        ->execute([$sel_date, $unit_id]);

    $stmt = $pdo->prepare("
        INSERT INTO patient_medication_tracking 
            (tracking_date, unit_id, patient_name, medical_number, drug_compatibility,
             antibiotic_program, high_risk_drugs, strict_priority, error_documentation,
             drug_definition, medication_description, pharmacist_name, created_by)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");

    $count = 0;
    foreach ($data as $row) {
        $stmt->execute([
            $sel_date,
            $unit_id,
            $row['patient_name']           ?? '',
            $row['medical_number']         ?? '',
            $row['drug_compatibility']     ?? 0,
            $row['antibiotic_program']     ?? 0,
            $row['high_risk_drugs']        ?? 0,
            $row['strict_priority']        ?? 0,
            $row['error_documentation']    ?? 0,
            $row['drug_definition']        ?? 0,
            $row['medication_description'] ?? '',
            $_SESSION['full_name'] ?? $_SESSION['username'] ?? 'غير محدد',
            $_SESSION['user_id']
        ]);
        $count++;
    }

    logActivity($pdo, $_SESSION['user_id'], 'حفظ بيانات KPI', 'patient_medication_tracking');

    echo json_encode(['success' => true, 'count' => $count, 'message' => "تم حفظ {$count} سجل بنجاح"]);

} catch (Exception $e) {
    error_log("KPI save error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'خطأ في الحفظ: ' . $e->getMessage()]);
}
