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

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

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header("Location: " . (isset($_SERVER["HTTPS"]) ? "https" : "http") . "://" . $_SERVER["HTTP_HOST"] . rtrim(dirname($_SERVER["SCRIPT_NAME"]), "/\\") . "/" . "manage_patients.php");
    exit();
}

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

// Get patient data
$stmt = $conn->prepare("SELECT * FROM patients WHERE id = :id");
$stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
$patient = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$patient) {
    header("Location: " . (isset($_SERVER["HTTPS"]) ? "https" : "http") . "://" . $_SERVER["HTTP_HOST"] . rtrim(dirname($_SERVER["SCRIPT_NAME"]), "/\\") . "/" . "manage_patients.php");
    exit();
}

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

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        // Validate MRN uniqueness (excluding current patient)
        $stmt = $conn->prepare("SELECT id FROM patients WHERE mrn = :mrn AND id != :id");
        $stmt->execute([':mrn' => $_POST['mrn'], ':id' => $_GET['id']]);
        
        if ($stmt->rowCount() > 0) {
            $error = __('mrn_already_exists_error');
        } else {
            $units = isset($_POST['units']) ? $_POST['units'] : [];
            $units_json = json_encode($units);
            
            $stmt = $conn->prepare("
                UPDATE patients SET 
                    patient_name = :patient_name,
                    mrn = :mrn,
                    gender = :gender,
                    age = :age,
                    phone = :phone,
                    units = :units,
                    updated_at = NOW()
                WHERE id = :id
            ");
            
            $stmt->execute([
                ':patient_name' => $_POST['patient_name'],
                ':mrn' => $_POST['mrn'],
                ':gender' => $_POST['gender'],
                ':age' => $_POST['age'] ?? null,
                ':phone' => $_POST['phone'] ?? null,
                ':units' => $units_json,
                ':id' => $_GET['id']
            ]);
            
            logActivity($conn, $_SESSION['user_id'], 'تحديث بيانات المريض', 'patients', $_GET['id']);
            $message = __('patient_updated_successfully');
            
            // Refresh patient data
            $stmt = $conn->prepare("SELECT * FROM patients WHERE id = :id");
            $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
            $stmt->execute();
            $patient = $stmt->fetch(PDO::FETCH_ASSOC);
        }
    } catch (Exception $e) {
        $error = __('error_updating_patient') . ': ' . $e->getMessage();
    }
}

// Decode units for display
$patient_units = json_decode($patient['units'] ?? '[]', true) ?: [];

// Set page title
$page_title = __('edit_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 __('edit_patient_page'); ?></h1>
        <div>
            <a href="view_patient.php?id=<?php echo $patient['id']; ?>" class="btn btn-info me-2">
                <i class="fas fa-eye"></i> <?php echo __('view_patient'); ?>
            </a>
            <a href="manage_patients.php" class="btn btn-secondary">
                <i class="fas fa-arrow-<?php echo Translation::getDirection() == 'rtl' ? 'right' : 'left'; ?>"></i> <?php echo __('back_to_patients'); ?>
            </a>
        </div>
    </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">
        <!-- Form -->
        <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 __('edit_patient_information'); ?></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($patient['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($patient['mrn']); ?>" required>
                                <div class="invalid-feedback">
                                    <?php echo __('please_enter_mrn'); ?>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-4 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 $patient['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 $patient['gender'] == 'female' ? 'checked' : ''; ?> required>
                                        <label class="form-check-label" for="female"><?php echo __('female'); ?></label>
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label for="age" class="form-label"><?php echo __('age_label'); ?></label>
                                <input type="number" class="form-control" id="age" name="age" 
                                       placeholder="<?php echo __('age_label'); ?>" value="<?php echo htmlspecialchars($patient['age'] ?? ''); ?>" min="0" max="150">
                            </div>

                            <div class="col-md-4 mb-3">
                                <label for="phone" class="form-label"><?php echo __('phone_label'); ?></label>
                                <input type="tel" class="form-control" id="phone" name="phone" 
                                       placeholder="<?php echo __('phone_label'); ?>" value="<?php echo htmlspecialchars($patient['phone'] ?? ''); ?>">
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><?php echo __('units_label'); ?> *</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'
                                ];
                                ?>
                                <?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, $patient_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_department'); ?></div>
                        </div>

                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save"></i> <?php echo __('save_changes'); ?>
                            </button>
                            <a href="view_patient.php?id=<?php echo $patient['id']; ?>" class="btn btn-info">
                                <i class="fas fa-eye"></i> <?php echo __('view_patient'); ?>
                            </a>
                            <a href="manage_patients.php" class="btn btn-secondary">
                                <i class="fas fa-times"></i> <?php echo __('cancel'); ?>
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Patient Info Summary -->
        <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 __('current_patient_information'); ?></h6>
                </div>
                <div class="card-body">
                    <div class="text-center mb-3">
                        <div class="avatar-circle bg-primary text-white mb-2">
                            <i class="fas fa-user fa-2x"></i>
                        </div>
                        <h6 class="mb-0"><?php echo htmlspecialchars($patient['patient_name']); ?></h6>
                        <p class="text-muted small"><?php echo __('file_number'); ?>: <?php echo htmlspecialchars($patient['mrn']); ?></p>
                    </div>

                    <hr>

                    <div class="mb-2">
                        <strong class="text-muted small"><?php echo __('gender'); ?>:</strong>
                        <span class="float-end"><?php echo $patient['gender'] == 'male' ? __('male') : __('female'); ?></span>
                    </div>

                    <div class="mb-2">
                        <strong class="text-muted small"><?php echo __('age_label'); ?>:</strong>
                        <span class="float-end"><?php echo htmlspecialchars($patient['age'] ?? __('not_specified')); ?></span>
                    </div>

                    <div class="mb-2">
                        <strong class="text-muted small"><?php echo __('phone_label'); ?>:</strong>
                        <span class="float-end"><?php echo htmlspecialchars($patient['phone'] ?? __('not_specified')); ?></span>
                    </div>

                    <div class="mb-2">
                        <strong class="text-muted small"><?php echo __('date_added'); ?>:</strong>
                        <span class="float-end"><?php echo date('Y-m-d', strtotime($patient['created_at'])); ?></span>
                    </div>

                    <?php if (!empty($patient_units)): ?>
                    <div class="mb-2">
                        <strong class="text-muted small"><?php echo __('current_departments'); ?>:</strong>
                        <div class="mt-2">
                            <?php foreach ($patient_units as $unit): ?>
                            <span class="badge bg-info me-1 mb-1 small"><?php echo htmlspecialchars($unit); ?></span>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <div class="card shadow mt-3">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-warning"><?php echo __('edit_instructions_note'); ?></h6>
                </div>
                <div class="card-body">
                    <ul class="list-unstyled mb-0 small">
                        <li class="mb-2">
                            <i class="fas fa-info-circle text-info me-2"></i>
                            <?php echo __('verify_mrn_accuracy'); ?>
                        </li>
                        <li class="mb-2">
                            <i class="fas fa-check text-success me-2"></i>
                            <?php echo __('select_appropriate_departments'); ?>
                        </li>
                        <li class="mb-2">
                            <i class="fas fa-save text-primary me-2"></i>
                            <?php echo __('save_after_verification'); ?>
                        </li>
                        <li>
                            <i class="fas fa-history text-warning me-2"></i>
                            <?php echo __('edit_history_saved'); ?>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.avatar-circle {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto;
}
</style>

<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_department'); ?>');
                    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'; ?>
