<?php
require_once __DIR__ . '/db/config.php';
require_once __DIR__ . '/helpers.php';

require_once __DIR__ . '/includes/auth.php';
check_auth();

$db = db();

// Handle Form Submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        try {
            if ($_POST['action'] === 'add_service') {
                $stmt = $db->prepare("INSERT INTO services (name_en, name_ar, department_id, price, is_active) VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([
                    $_POST['name_en'],
                    $_POST['name_ar'],
                    $_POST['department_id'],
                    $_POST['price'],
                    isset($_POST['is_active']) ? 1 : 0
                ]);
                $_SESSION['flash_message'] = '<div class="alert alert-success">' . __('service_added_successfully') . '</div>';
            } elseif ($_POST['action'] === 'edit_service') {
                $stmt = $db->prepare("UPDATE services SET name_en = ?, name_ar = ?, department_id = ?, price = ?, is_active = ? WHERE id = ?");
                $stmt->execute([
                    $_POST['name_en'],
                    $_POST['name_ar'],
                    $_POST['department_id'],
                    $_POST['price'],
                    isset($_POST['is_active']) ? 1 : 0,
                    $_POST['id']
                ]);
                $_SESSION['flash_message'] = '<div class="alert alert-success">' . __('service_updated_successfully') . '</div>';
            } elseif ($_POST['action'] === 'delete_service') {
                $stmt = $db->prepare("DELETE FROM services WHERE id = ?");
                $stmt->execute([$_POST['id']]);
                $_SESSION['flash_message'] = '<div class="alert alert-success">' . __('service_deleted_successfully') . '</div>';
            }
            // Redirect after successful operation
            header("Location: hospital_services.php");
            exit;
        } catch (PDOException $e) {
            $_SESSION['flash_message'] = '<div class="alert alert-danger">' . __('error') . ': ' . $e->getMessage() . '</div>';
            // Redirect even on error, so the user sees the message
            header("Location: hospital_services.php");
            exit;
        }
    }
}

// Session check logic (if needed in future)
// if (!isset($_SESSION['user_id'])) { ... }

$section = 'services';
$title = __('services');

require_once __DIR__ . '/includes/layout/header.php';
require_once __DIR__ . '/includes/pages/services.php';
require_once __DIR__ . '/includes/layout/footer.php';
