<?php
session_start();
include 'layouts/session.php';
include 'layouts/main.php';
include 'layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$doctor_id = $_SESSION['user_id'];
$patient_id = $_GET['patient_id'] ?? 0;
$document_id = $_GET['document_id'] ?? 0;

// Get patient details
$patient_query = "SELECT p.*, u.full_name, u.email FROM patients p
                 INNER JOIN users u ON p.user_id = u.user_id
                 WHERE p.patient_id = ?";
$patient_stmt = $conn->prepare($patient_query);
$patient_stmt->bind_param("i", $patient_id);
$patient_stmt->execute();
$patient = $patient_stmt->get_result()->fetch_assoc();

if (!$patient) {
    $_SESSION['error_message'] = "Patient not found";
    header('Location: patient_search.php');
    exit();
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $conn->begin_transaction();
    
    try {
        $share_type = $_POST['share_type'];
        $recipient_email = $_POST['recipient_email'] ?? null;
        $recipient_name = $_POST['recipient_name'] ?? null;
        $expiry_days = $_POST['expiry_days'];
        $notes = $_POST['notes'] ?? null;
        $include_consultations = isset($_POST['include_consultations']) ? 1 : 0;
        $include_prescriptions = isset($_POST['include_prescriptions']) ? 1 : 0;
        $include_lab_results = isset($_POST['include_lab_results']) ? 1 : 0;
        $include_documents = isset($_POST['include_documents']) ? 1 : 0;
        
        // Calculate expiry date
        $expiry_date = date('Y-m-d H:i:s', strtotime("+{$expiry_days} days"));
        
        // Generate unique share token
        $share_token = bin2hex(random_bytes(32));
        
        // Insert share record
        $sql = "INSERT INTO medical_data_shares (
            patient_id, shared_by, share_token, share_type, 
            recipient_email, recipient_name, expiry_date, notes,
            include_consultations, include_prescriptions, include_lab_results, include_documents,
            status
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'ACTIVE')";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("iissssssii", 
            $patient_id, $doctor_id, $share_token, $share_type,
            $recipient_email, $recipient_name, $expiry_date, $notes,
            $include_consultations, $include_prescriptions, $include_lab_results, $include_documents
        );
        $stmt->execute();
        $share_id = $conn->insert_id;
        
        // If specific document, link it
        if ($document_id > 0) {
            $doc_sql = "INSERT INTO share_documents (share_id, document_id) VALUES (?, ?)";
            $doc_stmt = $conn->prepare($doc_sql);
            $doc_stmt->bind_param("ii", $share_id, $document_id);
            $doc_stmt->execute();
        }
        
        // Log activity
        $action = "CREATE";
        $module = "MEDICAL_DATA_SHARE";
        $ip_address = $_SERVER['REMOTE_ADDR'];
        
        $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, ip_address) 
                    VALUES (?, ?, ?, ?, ?)";
        $log_stmt = $conn->prepare($log_sql);
        $log_stmt->bind_param("issis", $_SESSION['user_id'], $action, $module, $share_id, $ip_address);
        $log_stmt->execute();
        
        // Send email notification
        $share_link = "https://" . $_SERVER['HTTP_HOST'] . "/view_shared_data.php?token=" . $share_token;
        
        // Email sending code here
        
        $conn->commit();
        
        $_SESSION['success_message'] = "Medical data shared successfully!";
        $_SESSION['share_link'] = $share_link;
        header('Location: share_medical_data.php?patient_id=' . $patient_id . '&success=1');
        exit();
        
    } catch (Exception $e) {
        $conn->rollback();
        $_SESSION['error_message'] = "Error sharing data: " . $e->getMessage();
    }
}

$show_success = isset($_GET['success']);
?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Share Medical Data')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Share Medical Data</h4>
                                <div class="page-title-right">
                                    <a href="patient_documents.php?patient_id=<?php echo $patient_id; ?>" class="btn btn-secondary">
                                        <i class="ri-arrow-left-line"></i> Back
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Patient Info Bar -->
                    <div class="row mb-3">
                        <div class="col-12">
                            <div class="card" style="background: linear-gradient(135deg, #2d7a2d, #26a69a); color: white;">
                                <div class="card-body">
                                    <h5 class="text-white mb-1"><?php echo htmlspecialchars($patient['full_name']); ?></h5>
                                    <p class="text-white-50 mb-0">
                                        <strong>Patient ID:</strong> <?php echo $patient['patient_number']; ?>
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <?php if ($show_success && isset($_SESSION['share_link'])): ?>
                    <!-- Success Message -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card border border-success">
                                <div class="card-body">
                                    <div class="text-center">
                                        <i class="ri-check-double-line text-success" style="font-size: 3rem;"></i>
                                        <h4 class="text-success mt-3">Data Shared Successfully!</h4>
                                        <p class="text-muted">Share the link below with the recipient:</p>
                                        <div class="input-group mb-3">
                                            <input type="text" class="form-control" id="shareLink" 
                                                   value="<?php echo $_SESSION['share_link']; ?>" readonly>
                                            <button class="btn btn-primary" type="button" id="copyLink">
                                                <i class="ri-file-copy-line me-1"></i> Copy Link
                                            </button>
                                        </div>
                                        <a href="share_medical_data.php?patient_id=<?php echo $patient_id; ?>" class="btn btn-soft-primary">
                                            <i class="ri-share-line me-1"></i> Share More Data
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php unset($_SESSION['share_link']); ?>
                    <?php endif; ?>

                    <form method="POST" id="shareForm">
                        <div class="row">
                            <div class="col-lg-8">
                                <!-- Recipient Information -->
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="card-title mb-0">Recipient Information</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Share Type <span class="text-danger">*</span></label>
                                                <select class="form-select" name="share_type" required>
                                                    <option value="">Select Type</option>
                                                    <option value="DOCTOR">Another Doctor/Specialist</option>
                                                    <option value="PATIENT">Patient/Family Member</option>
                                                    <option value="INSURANCE">Insurance Company</option>
                                                    <option value="OTHER">Other Healthcare Provider</option>
                                                </select>
                                            </div>

                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Recipient Name <span class="text-danger">*</span></label>
                                                <input type="text" class="form-control" name="recipient_name" 
                                                       placeholder="Full name of recipient" required>
                                            </div>

                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Recipient Email <span class="text-danger">*</span></label>
                                                <input type="email" class="form-control" name="recipient_email" 
                                                       placeholder="email@example.com" required>
                                            </div>

                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Access Valid For <span class="text-danger">*</span></label>
                                                <select class="form-select" name="expiry_days" required>
                                                    <option value="1">1 Day</option>
                                                    <option value="3">3 Days</option>
                                                    <option value="7" selected>7 Days</option>
                                                    <option value="14">14 Days</option>
                                                    <option value="30">30 Days</option>
                                                    <option value="90">90 Days</option>
                                                </select>
                                            </div>

                                            <div class="col-md-12 mb-3">
                                                <label class="form-label">Notes/Purpose</label>
                                                <textarea class="form-control" name="notes" rows="3"
                                                          placeholder="Purpose of sharing or any additional notes..."></textarea>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Data Selection -->
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="card-title mb-0">Select Data to Share</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="form-check mb-3">
                                            <input class="form-check-input" type="checkbox" name="include_consultations" 
                                                   id="includeConsultations" checked>
                                            <label class="form-check-label" for="includeConsultations">
                                                <strong>Consultation Records</strong>
                                                <p class="text-muted small mb-0">Medical history, diagnoses, and treatment plans</p>
                                            </label>
                                        </div>

                                        <div class="form-check mb-3">
                                            <input class="form-check-input" type="checkbox" name="include_prescriptions" 
                                                   id="includePrescriptions" checked>
                                            <label class="form-check-label" for="includePrescriptions">
                                                <strong>Prescriptions</strong>
                                                <p class="text-muted small mb-0">Medication history and current prescriptions</p>
                                            </label>
                                        </div>

                                        <div class="form-check mb-3">
                                            <input class="form-check-input" type="checkbox" name="include_lab_results" 
                                                   id="includeLabResults" checked>
                                            <label class="form-check-label" for="includeLabResults">
                                                <strong>Lab Results</strong>
                                                <p class="text-muted small mb-0">Laboratory test results and reports</p>
                                            </label>
                                        </div>

                                        <div class="form-check mb-3">
                                            <input class="form-check-input" type="checkbox" name="include_documents" 
                                                   id="includeDocuments" checked>
                                            <label class="form-check-label" for="includeDocuments">
                                                <strong>Documents</strong>
                                                <p class="text-muted small mb-0">Medical reports, imaging, and other documents</p>
                                            </label>
                                        </div>

                                        <div class="alert alert-warning mt-3">
                                            <i class="ri-information-line me-2"></i>
                                            <strong>Privacy Notice:</strong> Only share medical data when necessary and with authorized recipients. 
                                            The recipient will receive a secure link to access this information.
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-lg-4">
                                <!-- Security Info -->
                                <div class="card">
                                    <div class="card-header bg-success-subtle">
                                        <h5 class="card-title mb-0 text-success">
                                            <i class="ri-shield-check-line me-2"></i>Security Features
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <ul class="list-unstyled mb-0">
                                            <li class="mb-2">
                                                <i class="ri-check-line text-success me-2"></i>
                                                Encrypted secure link
                                            </li>
                                            <li class="mb-2">
                                                <i class="ri-check-line text-success me-2"></i>
                                                Time-limited access
                                            </li>
                                            <li class="mb-2">
                                                <i class="ri-check-line text-success me-2"></i>
                                                Email notification sent
                                            </li>
                                            <li class="mb-2">
                                                <i class="ri-check-line text-success me-2"></i>
                                                Access tracking & logs
                                            </li>
                                            <li class="mb-2">
                                                <i class="ri-check-line text-success me-2"></i>
                                                Can be revoked anytime
                                            </li>
                                        </ul>
                                    </div>
                                </div>

                                <!-- Submit Button -->
                                <div class="card">
                                    <div class="card-body">
                                        <div class="d-grid gap-2">
                                            <button type="submit" class="btn btn-success btn-lg">
                                                <i class="ri-share-line me-1"></i> Generate Share Link
                                            </button>
                                            <a href="patient_documents.php?patient_id=<?php echo $patient_id; ?>" 
                                               class="btn btn-secondary btn-lg">
                                                <i class="ri-close-line me-1"></i> Cancel
                                            </a>
                                        </div>
                                    </div>
                                </div>

                                <!-- Active Shares -->
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="card-title mb-0">Active Shares</h5>
                                    </div>
                                    <div class="card-body">
                                        <div id="activeShares">
                                            <!-- Loaded via AJAX -->
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="assets/js/app.js"></script>
    
    <script>
        $(document).ready(function() {
            var patientId = <?php echo $patient_id; ?>;

            // Load active shares
            loadActiveShares();

            function loadActiveShares() {
                $.ajax({
                    url: 'ajax/get_active_shares.php',
                    type: 'POST',
                    data: { patient_id: patientId },
                    success: function(response) {
                        $('#activeShares').html(response);
                    }
                });
            }

            // Copy link
            $('#copyLink').on('click', function() {
                var copyText = document.getElementById('shareLink');
                copyText.select();
                document.execCommand('copy');
                
                Swal.fire({
                    icon: 'success',
                    title: 'Copied!',
                    text: 'Link copied to clipboard',
                    timer: 1500,
                    showConfirmButton: false
                });
            });

            // Revoke share
            $(document).on('click', '.btn-revoke-share', function() {
                var shareId = $(this).data('id');
                
                Swal.fire({
                    title: 'Revoke Access',
                    text: 'Are you sure you want to revoke this share? The recipient will no longer be able to access the data.',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, Revoke',
                    cancelButtonText: 'Cancel',
                    confirmButtonColor: '#d33'
                }).then((result) => {
                    if (result.isConfirmed) {
                        $.ajax({
                            url: 'ajax/revoke_share.php',
                            type: 'POST',
                            data: { share_id: shareId },
                            success: function(response) {
                                var result = JSON.parse(response);
                                if (result.success) {
                                    Swal.fire('Revoked!', 'Access has been revoked', 'success');
                                    loadActiveShares();
                                } else {
                                    Swal.fire('Error!', result.message, 'error');
                                }
                            }
                        });
                    }
                });
            });

            <?php if(isset($_SESSION['success_message'])): ?>
                Swal.fire({
                    icon: 'success',
                    title: 'Success',
                    text: '<?php echo $_SESSION['success_message']; ?>'
                });
                <?php unset($_SESSION['success_message']); ?>
            <?php endif; ?>

            <?php if(isset($_SESSION['error_message'])): ?>
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: '<?php echo $_SESSION['error_message']; ?>'
                });
                <?php unset($_SESSION['error_message']); ?>
            <?php endif; ?>
        });
    </script>
</body>
</html>