<?php
/**
 * Contact Requests - Phase 7
 * OBGYN Research & Collaboration Platform
 */

require_once '../config/config.php';

requireLogin();
if (!isResearcher()) {
    redirect(SITE_URL . '/index.php');
}

$pageTitle = 'Contact Requests';
$userId = getCurrentUserId();
$error = '';
$success = '';

// Handle approve/reject actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    validateCSRF();

    $action = $_POST['action'] ?? '';
    $requestId = (int)($_POST['request_id'] ?? 0);
    $responseMessage = sanitize($_POST['response_message'] ?? '');

    if ($action === 'approve' && $requestId > 0) {
        try {
            $db = getDB();
            $stmt = $db->prepare("
                UPDATE contact_requests
                SET status = 'approved', responded_at = NOW(), responded_by = ?, response_message = ?
                WHERE id = ? AND target_id = ?
            ");
            $stmt->execute([$userId, $responseMessage, $requestId, $userId]);
            $success = 'Contact request approved. The researcher can now view your contact information.';
        } catch (Exception $e) {
            $error = 'Failed to approve contact request.';
        }
    } elseif ($action === 'reject' && $requestId > 0) {
        try {
            $db = getDB();
            $stmt = $db->prepare("
                UPDATE contact_requests
                SET status = 'rejected', responded_at = NOW(), responded_by = ?, response_message = ?
                WHERE id = ? AND target_id = ?
            ");
            $stmt->execute([$userId, $responseMessage, $requestId, $userId]);
            $success = 'Contact request rejected.';
        } catch (Exception $e) {
            $error = 'Failed to reject contact request.';
        }
    }
}

// Get received contact requests
$db = getDB();
$stmt = $db->prepare("
    SELECT cr.*, u.first_name, u.last_name, u.email, u.institution, u.specialization, u.profile_picture
    FROM contact_requests cr
    JOIN users u ON cr.requester_id = u.id
    WHERE cr.target_id = ?
    ORDER BY cr.created_at DESC
");
$stmt->execute([$userId]);
$receivedRequests = $stmt->fetchAll();

// Get sent contact requests
$stmt = $db->prepare("
    SELECT cr.*, u.first_name, u.last_name, u.email, u.institution, u.specialization, u.profile_picture
    FROM contact_requests cr
    JOIN users u ON cr.target_id = u.id
    WHERE cr.requester_id = ?
    ORDER BY cr.created_at DESC
");
$stmt->execute([$userId]);
$sentRequests = $stmt->fetchAll();

include '../templates/researcher-header.php';
?>

<div class="container-fluid">
    <div class="row">
        <?php include 'sidebar.php'; ?>

        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
            <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-address-card"></i> Contact Requests</h1>
            </div>

            <?php if ($error): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <?php echo e($error); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <?php if ($success): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <?php echo e($success); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <!-- Received Requests Tab -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-inbox"></i> Received Requests (<?php echo count($receivedRequests); ?>)</h5>
                </div>
                <div class="card-body">
                    <?php if (empty($receivedRequests)): ?>
                        <p class="text-muted">No contact requests received yet.</p>
                    <?php else: ?>
                        <div class="row">
                            <?php foreach ($receivedRequests as $request): ?>
                                <div class="col-md-6 mb-3">
                                    <div class="card h-100">
                                        <div class="card-body">
                                            <div class="d-flex align-items-center mb-2">
                                                <img src="<?php echo getProfilePictureUrl($request['profile_picture']); ?>"
                                                     class="rounded-circle me-3" width="50" height="50" alt="Profile">
                                                <div>
                                                    <h6 class="mb-0"><?php echo e($request['first_name'] . ' ' . $request['last_name']); ?></h6>
                                                    <small class="text-muted"><?php echo e($request['institution']); ?></small>
                                                </div>
                                            </div>
                                            <p class="small text-muted mb-2"><?php echo e($request['specialization']); ?></p>
                                            <p class="small mb-2"><strong>Message:</strong> <?php echo e($request['message']); ?></p>
                                            <small class="text-muted d-block mb-3">
                                                Requested on <?php echo date('M d, Y', strtotime($request['created_at'])); ?>
                                            </small>

                                            <?php if ($request['status'] === 'pending'): ?>
                                                <div class="d-flex gap-2">
                                                    <button type="button" class="btn btn-sm btn-success"
                                                            onclick="respondToRequest(<?php echo $request['id']; ?>, 'approve')">
                                                        <i class="fas fa-check"></i> Approve
                                                    </button>
                                                    <button type="button" class="btn btn-sm btn-danger"
                                                            onclick="respondToRequest(<?php echo $request['id']; ?>, 'reject')">
                                                        <i class="fas fa-times"></i> Reject
                                                    </button>
                                                </div>
                                            <?php else: ?>
                                                <span class="badge bg-<?php echo $request['status'] === 'approved' ? 'success' : 'danger'; ?>">
                                                    <?php echo ucfirst($request['status']); ?>
                                                </span>
                                                <?php if ($request['response_message']): ?>
                                                    <p class="small mt-2"><strong>Your response:</strong> <?php echo e($request['response_message']); ?></p>
                                                <?php endif; ?>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Sent Requests Tab -->
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-paper-plane"></i> Sent Requests (<?php echo count($sentRequests); ?>)</h5>
                </div>
                <div class="card-body">
                    <?php if (empty($sentRequests)): ?>
                        <p class="text-muted">No contact requests sent yet.</p>
                    <?php else: ?>
                        <div class="row">
                            <?php foreach ($sentRequests as $request): ?>
                                <div class="col-md-6 mb-3">
                                    <div class="card h-100">
                                        <div class="card-body">
                                            <div class="d-flex align-items-center mb-2">
                                                <img src="<?php echo getProfilePictureUrl($request['profile_picture']); ?>"
                                                     class="rounded-circle me-3" width="50" height="50" alt="Profile">
                                                <div>
                                                    <h6 class="mb-0"><?php echo e($request['first_name'] . ' ' . $request['last_name']); ?></h6>
                                                    <small class="text-muted"><?php echo e($request['institution']); ?></small>
                                            </div>
                                        </div>
                                        <p class="small text-muted mb-2"><?php echo e($request['specialization']); ?></p>
                                        <p class="small mb-2"><strong>Your message:</strong> <?php echo e($request['message']); ?></p>
                                        <small class="text-muted d-block mb-3">
                                            Sent on <?php echo date('M d, Y', strtotime($request['created_at'])); ?>
                                        </small>
                                        <span class="badge bg-<?php echo $request['status'] === 'approved' ? 'success' : ($request['status'] === 'rejected' ? 'danger' : 'warning'); ?>">
                                            <?php echo ucfirst($request['status']); ?>
                                        </span>
                                        <?php if ($request['response_message']): ?>
                                            <p class="small mt-2"><strong>Response:</strong> <?php echo e($request['response_message']); ?></p>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>
</div>

<!-- Response Modal -->
<div class="modal fade" id="responseModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Respond to Contact Request</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <?php echo csrfField(); ?>
                <input type="hidden" name="request_id" id="modalRequestId">
                <input type="hidden" name="action" id="modalAction">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="responseMessage" class="form-label">Response Message (Optional)</label>
                        <textarea class="form-control" id="responseMessage" name="response_message" rows="3"
                                  placeholder="Add a personal message with your response..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn" id="modalSubmitBtn">Submit</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function respondToRequest(requestId, action) {
    document.getElementById('modalRequestId').value = requestId;
    document.getElementById('modalAction').value = action;

    const modal = new bootstrap.Modal(document.getElementById('responseModal'));
    const submitBtn = document.getElementById('modalSubmitBtn');

    if (action === 'approve') {
        submitBtn.className = 'btn btn-success';
        submitBtn.innerHTML = '<i class="fas fa-check"></i> Approve Request';
    } else {
        submitBtn.className = 'btn btn-danger';
        submitBtn.innerHTML = '<i class="fas fa-times"></i> Reject Request';
    }

    modal.show();
}
</script>

<?php include '../templates/researcher-mobile-footer.php'; ?>
</body>
</html>
