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

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

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

// إنشاء جدول سجل العمليات
try {
    $conn->exec("CREATE TABLE IF NOT EXISTS surgery_antibiotics_log (
        id INT AUTO_INCREMENT PRIMARY KEY,
        serial_number INT NOT NULL,
        patient_name VARCHAR(255),
        medical_number VARCHAR(100),
        surgery_type VARCHAR(255),
        consultant_name VARCHAR(255),
        antibiotic_id INT,
        antibiotic_code VARCHAR(50),
        quantity VARCHAR(50),
        unit_distinction VARCHAR(100),
        entry_time DATETIME,
        entry_status ENUM('تم', 'لم يتم') DEFAULT 'لم يتم',
        is_matched TINYINT(1) DEFAULT 0,
        report_date DATE,
        created_by INT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (antibiotic_id) REFERENCES antibiotics(id),
        FOREIGN KEY (created_by) REFERENCES users(id)
    )");
    
    // إضافة الأعمدة الجديدة إذا لم تكن موجودة
    $conn->exec("ALTER TABLE surgery_antibiotics_log 
                 ADD COLUMN IF NOT EXISTS unit_distinction VARCHAR(100) AFTER quantity");
    $conn->exec("ALTER TABLE surgery_antibiotics_log 
                 ADD COLUMN IF NOT EXISTS entry_status ENUM('تم', 'لم يتم') DEFAULT 'لم يتم' AFTER entry_time");
} catch (PDOException $e) {
    $error = __('error') . ': ' . $e->getMessage();
}

// جلب قائمة المضادات الحيوية
$antibiotics = [];
try {
    $stmt = $conn->query("SELECT id, antibiotic_name, generic_name, category FROM antibiotics WHERE is_active = 1 ORDER BY antibiotic_name");
    $antibiotics = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $error = __('error') . ': ' . $e->getMessage();
}

// معالجة الإضافة السريعة
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    try {
        if ($_POST['action'] == 'add_quick') {
            // الحصول على آخر رقم مسلسل
            $report_date = $_POST['report_date'];
            $stmt = $conn->prepare("SELECT MAX(serial_number) as max_serial FROM surgery_antibiotics_log WHERE report_date = ?");
            $stmt->execute([$report_date]);
            $result = $stmt->fetch();
            $next_serial = ($result['max_serial'] ?? 0) + 1;
            
            // جلب كود المضاد الحيوي
            $antibiotic_code = '';
            if (!empty($_POST['antibiotic_id'])) {
                $stmt = $conn->prepare("SELECT category FROM antibiotics WHERE id = ?");
                $stmt->execute([$_POST['antibiotic_id']]);
                $antibiotic = $stmt->fetch();
                $antibiotic_code = substr($antibiotic['category'] ?? '', 0, 3) . '-' . str_pad($_POST['antibiotic_id'], 4, '0', STR_PAD_LEFT);
            }
            
            $stmt = $conn->prepare("INSERT INTO surgery_antibiotics_log 
                (serial_number, patient_name, medical_number, surgery_type, consultant_name, 
                antibiotic_id, antibiotic_code, quantity, unit_distinction, entry_time, entry_status, is_matched, report_date, created_by) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            
            $stmt->execute([
                $next_serial,
                $_POST['patient_name'],
                $_POST['medical_number'],
                $_POST['surgery_type'],
                $_POST['consultant_name'],
                $_POST['antibiotic_id'] ?: null,
                $antibiotic_code,
                $_POST['quantity'],
                $_POST['unit_distinction'] ?? '',
                $_POST['entry_time'] ?: date('Y-m-d H:i:s'),
                $_POST['entry_status'] ?? 'لم يتم',
                isset($_POST['is_matched']) ? 1 : 0,
                $report_date,
                $_SESSION['user_id']
            ]);
            
            $message = __('record_added_success') . ' - ' . __('serial_number') . ': ' . $next_serial;
        } elseif ($_POST['action'] == 'delete') {
            $stmt = $conn->prepare("DELETE FROM surgery_antibiotics_log WHERE id = ?");
            $stmt->execute([$_POST['record_id']]);
            $message = __('record_deleted_success');
        } elseif ($_POST['action'] == 'toggle_match') {
            $stmt = $conn->prepare("UPDATE surgery_antibiotics_log SET is_matched = NOT is_matched WHERE id = ?");
            $stmt->execute([$_POST['record_id']]);
            $message = __('match_status_updated');
        } elseif ($_POST['action'] == 'toggle_entry_status') {
            $stmt = $conn->prepare("UPDATE surgery_antibiotics_log SET entry_status = ? WHERE id = ?");
            $new_status = $_POST['current_status'] == 'تم' ? 'لم يتم' : 'تم';
            $stmt->execute([$new_status, $_POST['record_id']]);
            $message = __('entry_status_updated');
        }
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}

// جلب السجلات
$report_date = $_GET['date'] ?? date('Y-m-d');
$records = [];
try {
    $stmt = $conn->prepare("
        SELECT sal.*, a.antibiotic_name, u.full_name as created_by_name
        FROM surgery_antibiotics_log sal
        LEFT JOIN antibiotics a ON sal.antibiotic_id = a.id
        LEFT JOIN users u ON sal.created_by = u.id
        WHERE sal.report_date = ?
        ORDER BY sal.serial_number ASC
    ");
    $stmt->execute([$report_date]);
    $records = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $error = __('error') . ': ' . $e->getMessage();
}

$page_title = __('medication_per_operation_page') . ' - ' . __('system_name');
include 'includes/header.php';
?>

<style>
.access-form {
    background: #f8f9fa;
    border: 2px solid #dee2e6;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
}

.access-form .form-row {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 10px;
    margin-bottom: 15px;
}

.access-form input,
.access-form select {
    padding: 8px;
    border: 1px solid #ced4da;
    border-radius: 4px;
    font-size: 0.9rem;
}

.access-form input:focus,
.access-form select:focus {
    outline: none;
    border-color: #667eea;
    box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
}

.access-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 0.85rem;
    background: white;
}

.access-table th,
.access-table td {
    border: 1px solid #dee2e6;
    padding: 6px;
    text-align: center;
}

.access-table th {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    font-weight: bold;
    position: sticky;
    top: 0;
    z-index: 10;
}

.access-table tbody tr:hover {
    background-color: #f1f3f5;
}

.access-table tbody tr.matched {
    background-color: #d4edda;
}

.access-table tbody tr.not-entered {
    background-color: #f8d7da;
}

.entry-status-done {
    color: #28a745;
    font-weight: bold;
}

.entry-status-not-done {
    color: #dc3545;
    font-weight: bold;
}

.entry-status-btn {
    padding: 4px 12px;
    border-radius: 4px;
    border: none;
    cursor: pointer;
    font-weight: bold;
    font-size: 0.85rem;
    transition: all 0.3s;
}

.entry-status-btn.done {
    background-color: #28a745;
    color: white;
}

.entry-status-btn.not-done {
    background-color: #dc3545;
    color: white;
}

.entry-status-btn:hover {
    opacity: 0.8;
    transform: scale(1.05);
}

.serial-col {
    width: 50px;
    background-color: #e9ecef;
    font-weight: bold;
}

.code-col {
    width: 100px;
    font-family: monospace;
    color: #495057;
}

.match-col {
    width: 60px;
}

.actions-col {
    width: 80px;
}

.table-container {
    max-height: 60vh;
    overflow-y: auto;
    border: 1px solid #dee2e6;
    border-radius: 8px;
}

.btn-add-quick {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border: none;
    padding: 10px 30px;
    border-radius: 6px;
    font-weight: bold;
    cursor: pointer;
    transition: all 0.3s;
}

.btn-add-quick:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.stats-bar {
    display: flex;
    gap: 20px;
    margin-bottom: 20px;
    padding: 15px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.stat-item {
    flex: 1;
    text-align: center;
    padding: 10px;
    border-radius: 6px;
}

.stat-item.total {
    background: #e3f2fd;
    color: #1976d2;
}

.stat-item.matched {
    background: #e8f5e9;
    color: #388e3c;
}

.stat-item.pending {
    background: #fff3e0;
    color: #f57c00;
}

.stat-number {
    font-size: 2rem;
    font-weight: bold;
}

.stat-label {
    font-size: 0.9rem;
    margin-top: 5px;
}

@media print {
    .no-print {
        display: none !important;
    }
}
</style>


    <div class="d-flex justify-content-between align-items-center mb-4 no-print">
        <h1 class="h3 mb-0">
            <i class="fas fa-procedures"></i>
            <?php echo __('medication_per_operation_title'); ?>
        </h1>
        <div>
            <input type="date" id="report_date" class="form-control d-inline-block" style="width: auto;" 
                   value="<?php echo $report_date; ?>" onchange="changeDate()">
            <button type="button" class="btn btn-success" onclick="window.print()">
                <i class="fas fa-print"></i> <?php echo __('print'); ?>
            </button>
            <button type="button" class="btn btn-info" onclick="exportToExcel()">
                <i class="fas fa-file-excel"></i> <?php echo __('export'); ?>
            </button>
            <a href="index.php" class="btn btn-secondary">
                <i class="fas fa-arrow-<?php echo Translation::getDirection() == 'rtl' ? 'right' : 'left'; ?>"></i> <?php echo __('back'); ?>
            </a>
        </div>
    </div>

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

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

    <!-- إحصائيات -->
    <div class="stats-bar no-print">
        <div class="stat-item total">
            <div class="stat-number"><?php echo count($records); ?></div>
            <div class="stat-label"><?php echo __('total_records'); ?></div>
        </div>
        <div class="stat-item matched">
            <div class="stat-number"><?php echo count(array_filter($records, fn($r) => $r['is_matched'])); ?></div>
            <div class="stat-label"><?php echo __('matched'); ?></div>
        </div>
        <div class="stat-item pending">
            <div class="stat-number"><?php echo count(array_filter($records, fn($r) => !$r['is_matched'])); ?></div>
            <div class="stat-label"><?php echo __('pending'); ?></div>
        </div>
    </div>

    <!-- نموذج الإدخال السريع -->
    <div class="access-form no-print">
        <h5 class="mb-3"><i class="fas fa-plus-circle"></i> <?php echo __('add_new_record'); ?></h5>
        <form method="POST" id="quickAddForm">
            <input type="hidden" name="action" value="add_quick">
            <input type="hidden" name="report_date" value="<?php echo $report_date; ?>">
            
            <div class="form-row">
                <div>
                    <label class="form-label small"><?php echo __('patient_name'); ?> *</label>
                    <input type="text" name="patient_name" class="form-control" required>
                </div>
                <div>
                    <label class="form-label small"><?php echo __('medical_number'); ?> *</label>
                    <input type="text" name="medical_number" class="form-control" required>
                </div>
                <div>
                    <label class="form-label small"><?php echo __('surgery_type'); ?> *</label>
                    <input type="text" name="surgery_type" class="form-control" required>
                </div>
                <div>
                    <label class="form-label small"><?php echo __('consultant_name'); ?> *</label>
                    <input type="text" name="consultant_name" class="form-control" required>
                </div>
            </div>
            
            <div class="form-row">
                <div>
                    <label class="form-label small"><?php echo __('medication_name'); ?> *</label>
                    <select name="antibiotic_id" class="form-control" required onchange="updateCode(this)">
                        <option value=""><?php echo __('select_medication'); ?></option>
                        <?php foreach ($antibiotics as $antibiotic): ?>
                            <option value="<?php echo $antibiotic['id']; ?>" 
                                    data-category="<?php echo $antibiotic['category']; ?>">
                                <?php echo htmlspecialchars($antibiotic['antibiotic_name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="form-label small"><?php echo __('code_auto'); ?></label>
                    <input type="text" id="antibiotic_code_display" class="form-control" readonly style="background: #e9ecef;">
                </div>
                <div>
                    <label class="form-label small"><?php echo __('quantity'); ?> *</label>
                    <input type="text" name="quantity" class="form-control" required>
                </div>
                <div>
                    <label class="form-label small"><?php echo __('unit_distinction'); ?> *</label>
                    <select name="unit_distinction" class="form-control" required>
                        <option value=""><?php echo __('select_unit'); ?></option>
                        <option value="أمبول"><?php echo __('ampoule'); ?></option>
                        <option value="قطارة"><?php echo __('dropper'); ?></option>
                        <option value="ملليتر"><?php echo __('milliliter'); ?></option>
                        <option value="زجاجة"><?php echo __('bottle'); ?></option>
                        <option value="أنبوبة"><?php echo __('tube'); ?></option>
                        <option value="فيال"><?php echo __('vial'); ?></option>
                    </select>
                </div>
                <div>
                    <label class="form-label small"><?php echo __('entry_status'); ?> *</label>
                    <select name="entry_status" class="form-control" required>
                        <option value="لم يتم"><?php echo __('not_done'); ?></option>
                        <option value="تم"><?php echo __('done'); ?></option>
                    </select>
                </div>
                <div>
                    <label class="form-label small"><?php echo __('entry_time'); ?></label>
                    <input type="datetime-local" name="entry_time" class="form-control" value="<?php echo date('Y-m-d\TH:i'); ?>">
                </div>
                <div class="d-flex align-items-end">
                    <div class="form-check">
                        <input type="checkbox" name="is_matched" class="form-check-input" id="is_matched">
                        <label class="form-check-label small" for="is_matched"><?php echo __('matched'); ?></label>
                    </div>
                </div>
            </div>
            
            <div class="text-center mt-3">
                <button type="submit" class="btn-add-quick">
                    <i class="fas fa-plus"></i> <?php echo __('add_new_record'); ?>
                </button>
            </div>
        </form>
    </div>

    <!-- الجدول -->
    <div class="card shadow">
        <div class="card-body p-0">
            <div class="table-container">
                <table class="access-table">
                    <thead>
                        <tr>
                            <th class="serial-col"><?php echo __('serial_number'); ?></th>
                            <th><?php echo __('patient_name'); ?></th>
                            <th><?php echo __('medical_number'); ?></th>
                            <th><?php echo __('surgery_type'); ?></th>
                            <th><?php echo __('consultant_name'); ?></th>
                            <th><?php echo __('medication_name'); ?></th>
                            <th class="code-col"><?php echo __('code'); ?></th>
                            <th><?php echo __('quantity'); ?></th>
                            <th><?php echo __('unit_distinction'); ?></th>
                            <th><?php echo __('entry_status'); ?></th>
                            <th class="match-col"><?php echo __('matched'); ?></th>
                            <th class="actions-col no-print"><?php echo __('actions'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($records)): ?>
                            <tr>
                                <td colspan="12" class="text-center text-muted py-4">
                                    <i class="fas fa-inbox fa-2x mb-2 d-block"></i>
                                    <?php echo __('no_records_for_date'); ?>
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($records as $record): ?>
                            <tr class="<?php echo $record['is_matched'] ? 'matched' : ''; ?> <?php echo ($record['entry_status'] ?? 'لم يتم') == 'لم يتم' ? 'not-entered' : ''; ?>">
                                <td class="serial-col"><?php echo $record['serial_number']; ?></td>
                                <td><?php echo htmlspecialchars($record['patient_name']); ?></td>
                                <td><?php echo htmlspecialchars($record['medical_number']); ?></td>
                                <td><?php echo htmlspecialchars($record['surgery_type']); ?></td>
                                <td><?php echo htmlspecialchars($record['consultant_name']); ?></td>
                                <td><?php echo htmlspecialchars($record['antibiotic_name'] ?? '-'); ?></td>
                                <td class="code-col"><?php echo htmlspecialchars($record['antibiotic_code']); ?></td>
                                <td><?php echo htmlspecialchars($record['quantity']); ?></td>
                                <td><?php echo htmlspecialchars($record['unit_distinction'] ?? '-'); ?></td>
                                <td>
                                    <form method="POST" style="display: inline;">
                                        <input type="hidden" name="action" value="toggle_entry_status">
                                        <input type="hidden" name="record_id" value="<?php echo $record['id']; ?>">
                                        <input type="hidden" name="current_status" value="<?php echo htmlspecialchars($record['entry_status'] ?? 'لم يتم'); ?>">
                                        <button type="submit" class="entry-status-btn <?php echo ($record['entry_status'] ?? 'لم يتم') == 'تم' ? 'done' : 'not-done'; ?>" 
                                                title="<?php echo __('click_to_change'); ?>">
                                            <?php 
                                            $status = $record['entry_status'] ?? 'لم يتم';
                                            echo $status == 'تم' ? __('done') : __('not_done');
                                            ?>
                                        </button>
                                    </form>
                                </td>
                                <td class="match-col">
                                    <form method="POST" style="display: inline;">
                                        <input type="hidden" name="action" value="toggle_match">
                                        <input type="hidden" name="record_id" value="<?php echo $record['id']; ?>">
                                        <button type="submit" class="btn btn-sm btn-<?php echo $record['is_matched'] ? 'success' : 'secondary'; ?>" 
                                                title="<?php echo $record['is_matched'] ? __('matched') : __('pending'); ?>">
                                            <i class="fas fa-<?php echo $record['is_matched'] ? 'check' : 'times'; ?>"></i>
                                        </button>
                                    </form>
                                </td>
                                <td class="actions-col no-print">
                                    <form method="POST" style="display: inline;" onsubmit="return confirm('<?php echo __('confirm_delete_record'); ?>');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="record_id" value="<?php echo $record['id']; ?>">
                                        <button type="submit" class="btn btn-sm btn-danger" title="<?php echo __('delete'); ?>">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script>
function changeDate() {
    const date = document.getElementById('report_date').value;
    window.location.href = 'medication_dispensed_per_operation.php?date=' + date;
}

function exportToExcel() {
    const date = document.getElementById('report_date').value;
    window.location.href = 'export/surgery_antibiotics_excel.php?date=' + date;
}

function updateCode(select) {
    const selectedOption = select.options[select.selectedIndex];
    const category = selectedOption.getAttribute('data-category') || '';
    const id = select.value;
    
    if (id) {
        const code = category.substring(0, 3).toUpperCase() + '-' + id.padStart(4, '0');
        document.getElementById('antibiotic_code_display').value = code;
    } else {
        document.getElementById('antibiotic_code_display').value = '';
    }
}

// Auto-focus on first input after form submit
document.addEventListener('DOMContentLoaded', function() {
    const firstInput = document.querySelector('#quickAddForm input[name="patient_name"]');
    if (firstInput) {
        firstInput.focus();
    }
});

// Reset form after successful submission
<?php if ($message && strpos($message, 'تم إضافة') !== false): ?>
document.getElementById('quickAddForm').reset();
document.querySelector('#quickAddForm input[name="patient_name"]').focus();
<?php endif; ?>
</script>

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

