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

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

// Set current page for permissions
$currentPage = 'advanced_search';

// Check page access permission
PagePermissions::requirePageAccess($currentPage);

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

$search_results = [];
$search_performed = false;

// Handle search
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $search_performed = true;
    
    $patient_name = sanitizeInput($_POST['patient_name'] ?? '');
    $mrn = sanitizeInput($_POST['mrn'] ?? '');
    $antibiotic_id = intval($_POST['antibiotic_id'] ?? 0);
    $unit_id = intval($_POST['unit_id'] ?? 0);
    $date_from = $_POST['date_from'] ?? '';
    $date_to = $_POST['date_to'] ?? '';
    $status = $_POST['status'] ?? '';
    $age_from = intval($_POST['age_from'] ?? 0);
    $age_to = intval($_POST['age_to'] ?? 0);
    $gender = $_POST['gender'] ?? '';
    
    try {
        $sql = "
            SELECT 
                ar.id,
                ar.report_date,
                ar.status,
                ar.created_at,
                p.patient_name,
                p.mrn,
                p.age,
                p.gender,
                p.diagnosis,
                u.unit_name,
                COALESCE(a.antibiotic_name, ar.other_medication_name, 'غير محدد') as antibiotic_name,
                ar.drug_type,
                usr.full_name as created_by_name
            FROM antibiotic_reports ar
            JOIN patients p ON ar.patient_id = p.id
            JOIN units u ON ar.unit_id = u.id
            LEFT JOIN antibiotics a ON ar.antibiotic_id = a.id
            JOIN users usr ON ar.created_by = usr.id
            WHERE 1=1
        ";
        
        $params = [];
        
        if (!empty($patient_name)) {
            $sql .= " AND p.patient_name LIKE ?";
            $params[] = "%$patient_name%";
        }
        
        if (!empty($mrn)) {
            $sql .= " AND p.mrn LIKE ?";
            $params[] = "%$mrn%";
        }
        
        if ($antibiotic_id > 0) {
            $sql .= " AND ar.antibiotic_id = ?";
            $params[] = $antibiotic_id;
        }
        
        if ($unit_id > 0) {
            $sql .= " AND ar.unit_id = ?";
            $params[] = $unit_id;
        }
        
        if (!empty($date_from)) {
            $sql .= " AND ar.report_date >= ?";
            $params[] = $date_from;
        }
        
        if (!empty($date_to)) {
            $sql .= " AND ar.report_date <= ?";
            $params[] = $date_to;
        }
        
        if (!empty($status)) {
            $sql .= " AND ar.status = ?";
            $params[] = $status;
        }
        
        if ($age_from > 0) {
            $sql .= " AND p.age >= ?";
            $params[] = $age_from;
        }
        
        if ($age_to > 0) {
            $sql .= " AND p.age <= ?";
            $params[] = $age_to;
        }
        
        if (!empty($gender)) {
            $sql .= " AND p.gender = ?";
            $params[] = $gender;
        }
        
        $sql .= " ORDER BY ar.created_at DESC LIMIT 100";
        
        $stmt = $conn->prepare($sql);
        $stmt->execute($params);
        $search_results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
    } catch (Exception $e) {
        $error = 'خطأ في البحث: ' . $e->getMessage();
    }
}

// Get antibiotics for dropdown
$antibiotics = [];
try {
    $stmt = $conn->query("SELECT id, antibiotic_name FROM antibiotics WHERE is_active = 1 ORDER BY antibiotic_name");
    $antibiotics = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    // Handle error silently
}

// Get units for dropdown
$units = [];
try {
    $stmt = $conn->query("SELECT id, unit_name FROM units WHERE is_active = 1 ORDER BY unit_name");
    $units = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    // Handle error silently
}

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


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

    <!-- Search Form -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary"><?php echo __('search_criteria'); ?></h6>
        </div>
        <div class="card-body">
            <form method="POST" id="searchForm">
                <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" 
                               value="<?php echo htmlspecialchars($_POST['patient_name'] ?? ''); ?>" 
                               placeholder="<?php echo __('search_patients'); ?>">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label for="mrn" class="form-label"><?php echo __('mrn'); ?></label>
                        <input type="text" class="form-control" id="mrn" name="mrn" 
                               value="<?php echo htmlspecialchars($_POST['mrn'] ?? ''); ?>" 
                               placeholder="<?php echo __('mrn'); ?>">
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label for="antibiotic_id" class="form-label"><?php echo __('antibiotic'); ?></label>
                        <select class="form-select" id="antibiotic_id" name="antibiotic_id">
                            <option value=""><?php echo __('all_antibiotics'); ?></option>
                            <?php foreach ($antibiotics as $antibiotic): ?>
                            <option value="<?php echo $antibiotic['id']; ?>" 
                                    <?php echo (isset($_POST['antibiotic_id']) && $_POST['antibiotic_id'] == $antibiotic['id']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($antibiotic['antibiotic_name']); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label for="unit_id" class="form-label"><?php echo __('unit'); ?></label>
                        <select class="form-select" id="unit_id" name="unit_id">
                            <option value=""><?php echo __('all_departments'); ?></option>
                            <?php foreach ($units as $unit): ?>
                            <option value="<?php echo $unit['id']; ?>" 
                                    <?php echo (isset($_POST['unit_id']) && $_POST['unit_id'] == $unit['id']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($unit['unit_name']); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label for="date_from" class="form-label"><?php echo __('date_from'); ?></label>
                        <input type="date" class="form-control" id="date_from" name="date_from" 
                               value="<?php echo $_POST['date_from'] ?? ''; ?>">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label for="date_to" class="form-label"><?php echo __('date_to'); ?></label>
                        <input type="date" class="form-control" id="date_to" name="date_to" 
                               value="<?php echo $_POST['date_to'] ?? ''; ?>">
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-4 mb-3">
                        <label for="status" class="form-label"><?php echo __('status'); ?></label>
                        <select class="form-select" id="status" name="status">
                            <option value=""><?php echo __('all_status'); ?></option>
                            <option value="pending" <?php echo (isset($_POST['status']) && $_POST['status'] == 'pending') ? 'selected' : ''; ?>><?php echo __('pending'); ?></option>
                            <option value="completed" <?php echo (isset($_POST['status']) && $_POST['status'] == 'completed') ? 'selected' : ''; ?>><?php echo __('completed'); ?></option>
                            <option value="cancelled" <?php echo (isset($_POST['status']) && $_POST['status'] == 'cancelled') ? 'selected' : ''; ?>><?php echo __('cancelled'); ?></option>
                        </select>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label for="gender" class="form-label"><?php echo __('gender'); ?></label>
                        <select class="form-select" id="gender" name="gender">
                            <option value=""><?php echo __('all_genders'); ?></option>
                            <option value="male" <?php echo (isset($_POST['gender']) && $_POST['gender'] == 'male') ? 'selected' : ''; ?>><?php echo __('male'); ?></option>
                            <option value="female" <?php echo (isset($_POST['gender']) && $_POST['gender'] == 'female') ? 'selected' : ''; ?>><?php echo __('female'); ?></option>
                        </select>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label"><?php echo __('age'); ?></label>
                        <div class="input-group">
                            <input type="number" class="form-control" name="age_from" placeholder="<?php echo __('from_date'); ?>" 
                                   value="<?php echo $_POST['age_from'] ?? ''; ?>" min="0" max="150">
                            <span class="input-group-text"><?php echo __('to_date'); ?></span>
                            <input type="number" class="form-control" name="age_to" placeholder="<?php echo __('to_date'); ?>" 
                                   value="<?php echo $_POST['age_to'] ?? ''; ?>" min="0" max="150">
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-12">
                        <?php if (PagePermissions::hasPermission($currentPage, 'use_advanced_search')): ?>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-search"></i> <?php echo __('search_button'); ?>
                        </button>
                        <button type="button" class="btn btn-secondary" onclick="clearForm()">
                            <i class="fas fa-eraser"></i> <?php echo __('clear_search'); ?>
                        </button>
                        <?php endif; ?>
                        
                        <?php if ($search_performed && !empty($search_results) && PagePermissions::hasPermission($currentPage, 'export_search_results')): ?>
                        <button type="button" class="btn btn-success" onclick="exportSearchResults()">
                            <i class="fas fa-file-excel"></i> <?php echo __('export_excel'); ?>
                        </button>
                        <?php endif; ?>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Search Results -->
    <?php if ($search_performed): ?>
    <div class="card shadow">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">
                <?php echo __('search_results'); ?> (<?php echo count($search_results); ?> <?php echo __('results_count'); ?>)
            </h6>
        </div>
        <div class="card-body">
            <?php if (empty($search_results)): ?>
                <div class="text-center py-4">
                    <i class="fas fa-search fa-3x text-muted mb-3"></i>
                    <h5 class="text-muted"><?php echo __('no_search_results'); ?></h5>
                    <p class="text-muted"><?php echo __('no_search_results_message'); ?></p>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-bordered" id="searchResultsTable">
                        <thead>
                            <tr>
                                <th><?php echo __('date'); ?></th>
                                <th><?php echo __('file_number'); ?></th>
                                <th><?php echo __('patient_name'); ?></th>
                                <th><?php echo __('age'); ?>/<?php echo __('gender'); ?></th>
                                <th><?php echo __('antibiotic'); ?></th>
                                <th><?php echo __('unit'); ?></th>
                                <th><?php echo __('diagnosis'); ?></th>
                                <th><?php echo __('status'); ?></th>
                                <th><?php echo __('created_by'); ?></th>
                                <th><?php echo __('actions'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($search_results as $result): ?>
                            <tr>
                                <td><?php echo formatArabicDate($result['report_date']); ?></td>
                                <td><?php echo htmlspecialchars($result['mrn']); ?></td>
                                <td><?php echo htmlspecialchars($result['patient_name']); ?></td>
                                <td>
                                    <?php echo $result['age']; ?> <?php echo __('year'); ?><br>
                                    <small class="text-muted"><?php echo $result['gender'] == 'male' ? __('male') : __('female'); ?></small>
                                </td>
                                <td><?php echo htmlspecialchars($result['antibiotic_name']); ?></td>
                                <td><?php echo htmlspecialchars($result['unit_name']); ?></td>
                                <td>
                                    <small><?php echo htmlspecialchars(substr($result['diagnosis'], 0, 50)); ?>
                                    <?php echo strlen($result['diagnosis']) > 50 ? '...' : ''; ?></small>
                                </td>
                                <td>
                                    <span class="badge bg-<?php 
                                        switch($result['status']) {
                                            case 'completed': echo 'success'; break;
                                            case 'pending': echo 'warning'; break;
                                            case 'cancelled': echo 'danger'; break;
                                            default: echo 'secondary';
                                        }
                                    ?>">
                                        <?php 
                                        switch($result['status']) {
                                            case 'completed': echo __('completed'); break;
                                            case 'pending': echo __('pending'); break;
                                            case 'cancelled': echo __('cancelled'); break;
                                            default: echo $result['status'];
                                        }
                                        ?>
                                    </span>
                                </td>
                                <td><?php echo htmlspecialchars($result['created_by_name']); ?></td>
                                <td>
                                    <a href="view_medical_event.php?id=<?php echo $result['id']; ?>" class="btn btn-sm btn-info">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                    <a href="edit_report.php?id=<?php echo $result['id']; ?>" class="btn btn-sm btn-warning">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <a href="print_report.php?id=<?php echo $result['id']; ?>" class="btn btn-sm btn-secondary" target="_blank">
                                        <i class="fas fa-print"></i>
                                    </a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>
</div>

<script>
function clearForm() {
    document.getElementById('searchForm').reset();
}

function exportSearchResults() {
    // Create a form to submit search parameters for export
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = 'export/search_results_excel.php';
    
    // Copy all search parameters
    const formData = new FormData(document.getElementById('searchForm'));
    for (let [key, value] of formData.entries()) {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = key;
        input.value = value;
        form.appendChild(input);
    }
    
    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form);
}

// Initialize DataTable for results
$(document).ready(function() {
    if ($('#searchResultsTable').length) {
        $('#searchResultsTable').DataTable({
            "language": {
                "url": "//cdn.datatables.net/plug-ins/1.10.24/i18n/Arabic.json"
            },
            "order": [[ 0, "desc" ]],
            "pageLength": 25,
            "scrollX": true
        });
    }
});
</script>

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