<?php
session_start();
require_once '../config.php';

requireAdmin();

$page_title = 'Doctor Verification';

// Handle verification actions
if ($_POST && isset($_POST['action']) && isset($_POST['doctor_id'])) {
    $doctor_id = (int)$_POST['doctor_id'];
    $action = $_POST['action'];
    $admin_notes = clean($_POST['admin_notes'] ?? '');

    if (in_array($action, ['approve', 'reject'])) {
        $status = $action === 'approve' ? 'approved' : 'rejected';
        
        $stmt = $conn->prepare("UPDATE doctors SET verification_status = ? WHERE id = ?");
        $stmt->bind_param('si', $status, $doctor_id);
        
        if ($stmt->execute()) {
            // Get doctor details for notification
            $doctor_stmt = $conn->prepare("SELECT full_name, email FROM doctors WHERE id = ?");
            $doctor_stmt->bind_param('i', $doctor_id);
            $doctor_stmt->execute();
            $doctor = $doctor_stmt->get_result()->fetch_assoc();
            
            // Send notification to doctor
            $notif_title = $status === 'approved' ? 'Account Approved' : 'Account Rejected';
            $notif_message = $status === 'approved' 
                ? 'Congratulations! Your doctor account has been approved. You can now login and start consultations.'
                : 'Your doctor account verification was rejected. Reason: ' . $admin_notes;
            
            $notif_stmt = $conn->prepare("
                INSERT INTO notifications (user_type, user_id, title, message, type, channel)
                VALUES ('doctor', ?, ?, ?, 'verification_status', 'email')
            ");
            $notif_stmt->bind_param('iss', $doctor_id, $notif_title, $notif_message);
            $notif_stmt->execute();
            
            setFlash('success', "Doctor {$doctor['full_name']} has been {$status}.");
        } else {
            setFlash('error', 'Failed to update verification status.');
        }
        
        header('Location: doctor-verification.php');
        exit;
    }
}

// Get pending doctors
$pending_doctors_result = $conn->query("
    SELECT d.*, s.name as specialization_name
    FROM doctors d
    LEFT JOIN specializations s ON d.specialization_id = s.id
    WHERE d.verification_status = 'pending'
    ORDER BY d.created_at ASC
");
$doctors_list = $pending_doctors_result ? $pending_doctors_result->fetch_all(MYSQLI_ASSOC) : [];
$pending_doctors_count = count($doctors_list);

// Get specific doctor for detailed view
$view_doctor = null;
if (isset($_GET['action']) && $_GET['action'] === 'view' && isset($_GET['id'])) {
    $doctor_id = (int)$_GET['id'];
    $view_stmt = $conn->prepare("
        SELECT d.*, s.name as specialization_name
        FROM doctors d
        LEFT JOIN specializations s ON d.specialization_id = s.id
        WHERE d.id = ? AND d.verification_status = 'pending'
    ");
    $view_stmt->bind_param('i', $doctor_id);
    $view_stmt->execute();
    $view_doctor = $view_stmt->get_result()->fetch_assoc();
}

include 'header.php';
?>

                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">
                        <i class="fas fa-user-check text-primary"></i> Doctor Verification (<?= $pending_doctors_count ?>)
                    </h1>
                </div>
            
            <?php if ($view_doctor): ?>
                <!-- Doctor Details View -->
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5><i class="fas fa-user-md"></i> Doctor Verification Details</h5>
                        <a href="doctor-verification.php" class="btn btn-sm btn-secondary">
                            <i class="fas fa-arrow-left"></i> Back to List
                        </a>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-4 text-center">
                                <?php if ($view_doctor['profile_photo']): ?>
                                    <img src="<?= SITE_URL ?>/<?= $view_doctor['profile_photo'] ?>" alt="Dr. <?= htmlspecialchars($view_doctor['full_name']) ?>" class="img-fluid rounded mb-3" style="max-width: 200px;">
                                <?php else: ?>
                                    <div class="bg-primary text-white rounded d-inline-flex align-items-center justify-content-center mb-3" style="width: 150px; height: 150px;">
                                        <i class="fas fa-user-md fa-4x"></i>
                                    </div>
                                <?php endif; ?>
                                
                                <h4>Dr. <?= htmlspecialchars($view_doctor['full_name']) ?></h4>
                                <p class="text-muted"><?= htmlspecialchars($view_doctor['specialization_name']) ?></p>
                            </div>
                            
                            <div class="col-md-8">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <strong>Email:</strong><br>
                                        <?= htmlspecialchars($view_doctor['email']) ?>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <strong>Phone:</strong><br>
                                        <?= htmlspecialchars($view_doctor['phone']) ?>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <strong>PMC License:</strong><br>
                                        <?= htmlspecialchars($view_doctor['pmc_license_number']) ?>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <strong>Experience:</strong><br>
                                        <?= $view_doctor['experience_years'] ?> years
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <strong>Qualification:</strong><br>
                                        <?= htmlspecialchars($view_doctor['qualification']) ?>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <strong>Consultation Fee:</strong><br>
                                        Rs. <?= number_format($view_doctor['consultation_fee']) ?>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <strong>Clinic Name:</strong><br>
                                        <?= htmlspecialchars($view_doctor['clinic_name']) ?>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <strong>City:</strong><br>
                                        <?= htmlspecialchars($view_doctor['city']) ?>
                                    </div>
                                </div>
                                
                                <?php if ($view_doctor['bio']): ?>
                                    <div class="mb-3">
                                        <strong>Bio:</strong><br>
                                        <?= htmlspecialchars($view_doctor['bio']) ?>
                                    </div>
                                <?php endif; ?>
                                
                                <div class="mb-3">
                                    <strong>Clinic Address:</strong><br>
                                    <?= htmlspecialchars($view_doctor['clinic_address']) ?>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Documents -->
                        <div class="row mt-4">
                            <div class="col-12">
                                <h6>Uploaded Documents</h6>
                                <div class="row">
                                    <?php if ($view_doctor['doc_license']): ?>
                                        <div class="col-md-4 mb-3">
                                            <div class="card">
                                                <div class="card-body text-center">
                                                    <i class="fas fa-file-alt fa-2x text-primary mb-2"></i>
                                                    <p class="small">PMC License</p>
                                                    <a href="<?= SITE_URL ?>/<?= $view_doctor['doc_license'] ?>" target="_blank" class="btn btn-sm btn-outline-primary">View</a>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                    
                                    <?php if ($view_doctor['doc_qualification']): ?>
                                        <div class="col-md-4 mb-3">
                                            <div class="card">
                                                <div class="card-body text-center">
                                                    <i class="fas fa-graduation-cap fa-2x text-success mb-2"></i>
                                                    <p class="small">Qualification Certificate</p>
                                                    <a href="<?= SITE_URL ?>/<?= $view_doctor['doc_qualification'] ?>" target="_blank" class="btn btn-sm btn-outline-success">View</a>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                    
                                    <?php if ($view_doctor['doc_cnic']): ?>
                                        <div class="col-md-4 mb-3">
                                            <div class="card">
                                                <div class="card-body text-center">
                                                    <i class="fas fa-id-card fa-2x text-info mb-2"></i>
                                                    <p class="small">CNIC Copy</p>
                                                    <a href="<?= SITE_URL ?>/<?= $view_doctor['doc_cnic'] ?>" target="_blank" class="btn btn-sm btn-outline-info">View</a>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Verification Actions -->
                        <div class="row mt-4">
                            <div class="col-12">
                                <div class="card bg-light">
                                    <div class="card-body">
                                        <h6>Verification Decision</h6>
                                        <form method="POST">
                                            <input type="hidden" name="doctor_id" value="<?= $view_doctor['id'] ?>">
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Admin Notes (optional)</label>
                                                <textarea name="admin_notes" class="form-control" rows="3" placeholder="Add any notes or rejection reasons..."></textarea>
                                            </div>
                                            
                                            <div class="d-flex gap-3">
                                                <button type="submit" name="action" value="approve" class="btn btn-success">
                                                    <i class="fas fa-check"></i> Approve Doctor
                                                </button>
                                                <button type="submit" name="action" value="reject" class="btn btn-danger">
                                                    <i class="fas fa-times"></i> Reject Application
                                                </button>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
            <?php else: ?>
                <!-- Pending Doctors List -->
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-exclamation-triangle text-warning"></i> Pending Doctor Verifications (<?= $pending_doctors_count ?>)</h5>
                    </div>
                    <div class="card-body">
                        <?php if (empty($doctors_list)): ?>
                            <div class="text-center">
                                <i class="fas fa-check-circle fa-5x text-success mb-4"></i>
                                <h4>No pending verifications</h4>
                                <p class="text-muted">All doctor applications have been processed.</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Doctor Details</th>
                                            <th>Specialization</th>
                                            <th>PMC License</th>
                                            <th>Experience</th>
                                            <th>Applied Date</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($doctors_list as $doctor): ?>
                                            <tr>
                                                <td>
                                                    <div class="d-flex align-items-center">
                                                        <?php if ($doctor['profile_photo']): ?>
                                                            <img src="<?= SITE_URL ?>/<?= $doctor['profile_photo'] ?>" alt="Dr. <?= htmlspecialchars($doctor['full_name']) ?>" class="rounded-circle me-3" width="50" height="50">
                                                        <?php else: ?>
                                                            <div class="bg-primary text-white rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 50px; height: 50px;">
                                                                <i class="fas fa-user-md"></i>
                                                            </div>
                                                        <?php endif; ?>
                                                        <div>
                                                            <strong>Dr. <?= htmlspecialchars($doctor['full_name']) ?></strong><br>
                                                            <small class="text-muted"><?= htmlspecialchars($doctor['email']) ?></small>
                                                        </div>
                                                    </div>
                                                </td>
                                                <td><?= htmlspecialchars($doctor['specialization_name']) ?></td>
                                                <td><code><?= htmlspecialchars($doctor['pmc_license_number']) ?></code></td>
                                                <td><?= $doctor['experience_years'] ?> years</td>
                                                <td><?= date('d M Y', strtotime($doctor['created_at'])) ?></td>
                                                <td>
                                                    <a href="doctor-verification.php?action=view&id=<?= $doctor['id'] ?>" class="btn btn-sm btn-primary">
                                                        <i class="fas fa-eye"></i> Review
                                                    </a>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endif; ?>

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