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

if (!isset($_SESSION['user_id'])) {
    redirect('login.php');
}

$page_title = __('add') . ' ' . __('patient_name') . ' - ' . __('system_name');

$db = new Database();
$conn = $db->getConnection();

$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Check if this is an AJAX request
    $is_ajax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
    
    $patient_name = trim($_POST['patient_name'] ?? '');
    $mrn = trim($_POST['mrn'] ?? '');
    $gender = $_POST['gender'] ?? '';
    $units = isset($_POST['units']) ? $_POST['units'] : [];
    $reporting_pharmacist_id = trim($_POST['reporting_pharmacist_id'] ?? $_POST['pharmacy_number'] ?? '');
    
    if (empty($patient_name) || empty($mrn) || empty($gender) || empty($units) || empty($reporting_pharmacist_id)) {
        $error = __('all_fields_required');
        error_log("Validation error: " . $error);
        if ($is_ajax) {
            header('Content-Type: application/json');
            echo json_encode([
                'success' => false, 
                'message' => $error,
                'data' => [
                    'patient_name' => $patient_name,
                    'mrn' => $mrn,
                    'gender' => $gender,
                    'units' => $units,
                    'reporting_pharmacist_id' => $reporting_pharmacist_id
                ]
            ]);
            exit();
        }
    } elseif (!validateMRN($mrn)) {
        $error = __('mrn_validation_error');
        if ($is_ajax) {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => $error]);
            exit();
        }
    } else {
        try {
            // Check if MRN already exists
            $stmt = $conn->prepare("SELECT id FROM patients WHERE mrn = ?");
            $stmt->execute([$mrn]);
            
            if ($stmt->fetch()) {
                $error = __('mrn_already_exists');
                if ($is_ajax) {
                    header('Content-Type: application/json');
                    echo json_encode(['success' => false, 'message' => $error]);
                    exit();
                }
            } else {
                // Insert new patient
                $units_json = json_encode($units);
                $stmt = $conn->prepare("
                    INSERT INTO patients (patient_name, mrn, gender, units, reporting_pharmacist_id) 
                    VALUES (?, ?, ?, ?, ?)
                ");
                $stmt->execute([$patient_name, $mrn, $gender, $units_json, $reporting_pharmacist_id]);
                
                $patient_id = $conn->lastInsertId();
                
                // Add patient to simple monitoring table automatically
                try {
                    $stmt_monitoring = $conn->prepare("
                        INSERT INTO simple_patient_monitoring 
                        (patient_id, report_date, created_by) 
                        VALUES (?, CURDATE(), ?)
                    ");
                    $stmt_monitoring->execute([$patient_id, $_SESSION['user_id']]);
                } catch (Exception $e) {
                    // Log error but don't stop the process
                    error_log("Error adding to monitoring table: " . $e->getMessage());
                }
                
                logActivity($conn, $_SESSION['user_id'], __('add_patient_activity'), 'patients', $patient_id);
                $message = __('patient_added_successfully');
                
                if ($is_ajax) {
                    header('Content-Type: application/json');
                    echo json_encode([
                        'success' => true, 
                        'message' => $message,
                        'patient_id' => $patient_id,
                        'patient_name' => $patient_name,
                        'mrn' => $mrn
                    ]);
                    exit();
                }
                
                // Clear form
                $_POST = [];
            }
        } catch (Exception $e) {
            $error = __('error_adding_patient') . ': ' . $e->getMessage();
            if ($is_ajax) {
                header('Content-Type: application/json');
                echo json_encode(['success' => false, 'message' => $error]);
                exit();
            }
        }
    }
}

// Set page title
$page_title = __('add_patient_page') . ' - ' . __('system_name');

// Include header
include 'includes/header.php';
?>

<!-- Main Content -->

    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="h3 mb-0"><?php echo __('add_patient_page'); ?></h1>
        <a href="manage_patients.php" class="btn btn-secondary">
            <i class="fas fa-arrow-right"></i> <?php echo __('back_to_patients'); ?>
        </a>
    </div>

    <?php if ($message): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle me-2"></i>
            <?php echo $message; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <?php if ($error): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-triangle me-2"></i>
            <?php echo $error; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <div class="row">
        <!-- Left Column - Form Fields -->
        <div class="col-md-8">
            <div class="card shadow">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary"><?php echo __('patient_basic_info'); ?></h6>
                </div>
                <div class="card-body">
                    <form method="POST" class="needs-validation" novalidate>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="patient_name" class="form-label"><?php echo __('patient_name'); ?> *</label>
                                <input type="text" class="form-control" id="patient_name" name="patient_name" 
                                       placeholder="<?php echo __('enter_patient_name'); ?>" value="<?php echo htmlspecialchars($_POST['patient_name'] ?? ''); ?>" required>
                                <div class="invalid-feedback">
                                    <?php echo __('please_enter_patient_name'); ?>
                                </div>
                            </div>

                            <div class="col-md-6 mb-3">
                                <label for="mrn" class="form-label"><?php echo __('mrn_label'); ?> *</label>
                                <input type="text" class="form-control" id="mrn" name="mrn" 
                                       placeholder="<?php echo __('mrn_example'); ?>" value="<?php echo htmlspecialchars($_POST['mrn'] ?? ''); ?>" required>
                                <div class="invalid-feedback">
                                    <?php echo __('please_enter_mrn'); ?>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label"><?php echo __('gender_label'); ?> *</label>
                                <div class="mt-2">
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="gender" value="male" id="male" 
                                               <?php echo ($_POST['gender'] ?? '') == 'male' ? 'checked' : ''; ?> required>
                                        <label class="form-check-label" for="male"><?php echo __('male'); ?></label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="gender" value="female" id="female" 
                                               <?php echo ($_POST['gender'] ?? '') == 'female' ? 'checked' : ''; ?> required>
                                        <label class="form-check-label" for="female"><?php echo __('female'); ?></label>
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-6 mb-3">
                                <label for="reporting_pharmacist_id" class="form-label"><?php echo __('reporting_pharmacist_id'); ?> *</label>
                                <input type="text" class="form-control" id="reporting_pharmacist_id" name="reporting_pharmacist_id" 
                                       placeholder="<?php echo __('pharmacist_id_example'); ?>" value="<?php echo htmlspecialchars($_POST['reporting_pharmacist_id'] ?? ''); ?>" required>
                                <div class="invalid-feedback">
                                    <?php echo __('please_enter_pharmacist_id'); ?>
                                </div>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><?php echo __('units_departments'); ?> *</label>
                            <div class="row mt-2">
                                <?php 
                                $units = [
                                    '6th Floor', '5th floor', '4th floor', '4th ICU', 'NICU', 'OR', 
                                    'CCU', 'Cath Lab', 'CICU', 'KU', 'Day care', 'GIT Lab', 'CABG unit'
                                ];
                                $selected_units = $_POST['units'] ?? [];
                                ?>
                                <?php foreach ($units as $index => $unit): ?>
                                    <?php if ($index % 3 == 0): ?>
                                        <div class="col-md-4">
                                    <?php endif; ?>
                                    
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" name="units[]" value="<?php echo $unit; ?>" 
                                               id="unit_<?php echo str_replace([' ', '.'], '_', $unit); ?>"
                                               <?php echo in_array($unit, $selected_units) ? 'checked' : ''; ?>>
                                        <label class="form-check-label" for="unit_<?php echo str_replace([' ', '.'], '_', $unit); ?>">
                                            <?php echo $unit; ?>
                                        </label>
                                    </div>
                                    
                                    <?php if (($index + 1) % 3 == 0 || $index == count($units) - 1): ?>
                                        </div>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </div>
                            <div class="form-text"><?php echo __('select_at_least_one_unit'); ?></div>
                        </div>

                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save"></i> <?php echo __('add_patient_button'); ?>
                            </button>
                            <a href="manage_patients.php" class="btn btn-secondary">
                                <i class="fas fa-times"></i> <?php echo __('cancel'); ?>
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Right Column - Instructions -->
        <div class="col-md-4">
            <div class="card shadow">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-info"><?php echo __('input_instructions'); ?></h6>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <h6 class="text-primary"><?php echo __('mrn_label'); ?></h6>
                        <p class="small text-muted"><?php echo __('mrn_instructions'); ?></p>
                    </div>
                    
                    <div class="mb-3">
                        <h6 class="text-primary"><?php echo __('patient_name'); ?></h6>
                        <p class="small text-muted"><?php echo __('patient_name_instructions'); ?></p>
                    </div>
                    
                    <div class="mb-3">
                        <h6 class="text-primary"><?php echo __('units_departments'); ?></h6>
                        <p class="small text-muted"><?php echo __('units_instructions'); ?></p>
                    </div>
                    
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle me-2"></i>
                        <strong><?php echo __('note'); ?>:</strong> <?php echo __('required_fields_note'); ?>
                    </div>
                </div>
            </div>
        </div>
        </div>
    </div>
</div>

<script>
// Form validation
(function() {
    'use strict';
    window.addEventListener('load', function() {
        var forms = document.getElementsByClassName('needs-validation');
        var validation = Array.prototype.filter.call(forms, function(form) {
            form.addEventListener('submit', function(event) {
                // Check if at least one unit is selected
                const units = document.querySelectorAll('input[name="units[]"]:checked');
                if (units.length === 0) {
                    event.preventDefault();
                    event.stopPropagation();
                    alert('<?php echo __('select_at_least_one_unit'); ?>');
                    return false;
                }
                
                if (form.checkValidity() === false) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                form.classList.add('was-validated');
            }, false);
        });
    }, false);
})();

// MRN validation
document.getElementById('mrn').addEventListener('input', function() {
    const mrn = this.value;
    const isValid = /^\d{4,10}$/.test(mrn);
    
    if (mrn && !isValid) {
        this.setCustomValidity('<?php echo __('mrn_must_be_4_10_digits'); ?>');
    } else {
        this.setCustomValidity('');
    }
});
</script>

<?php include 'includes/footer.php'; ?>
