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

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

$msg = "";
$patient_id = $_GET['patient_id'] ?? 0;

// Fetch patient info
if ($patient_id) {
    $p = $conn->query("SELECT p.patient_number, u.first_name, u.last_name 
                       FROM patients p JOIN users u ON p.user_id = u.user_id 
                       WHERE p.patient_id = $patient_id")->fetch_assoc();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['upload'])) {
    $pid = $_POST['patient_id'];
    $title = $_POST['title'];
    $type = $_POST['doc_type'];
    $desc = $_POST['description'];

    // File upload logic
    $target_dir = "uploads/medical_documents/";
    if (!file_exists($target_dir)) {
        mkdir($target_dir, 0777, true);
    }

    $file_name = basename($_FILES["doc_file"]["name"]);
    $target_file = $target_dir . time() . "_" . $file_name;
    $uploadOk = 1;
    $fileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

    // Allow certain file formats
    if ($fileType != "pdf" && $fileType != "jpg" && $fileType != "png" && $fileType != "jpeg") {
        $msg = "Sorry, only PDF, JPG, JPEG, & PNG files are allowed.";
        $uploadOk = 0;
    }

    if ($uploadOk) {
        if (move_uploaded_file($_FILES["doc_file"]["tmp_name"], $target_file)) {
            $stmt = $conn->prepare("INSERT INTO medical_documents (patient_id, document_type, document_title, document_description, file_path, file_name, file_type, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("issssssi", $pid, $type, $title, $desc, $target_file, $file_name, $fileType, $_SESSION['user_id']);
            if ($stmt->execute()) {
                $msg = "The file has been uploaded.";
                // Redirect or show success
            } else {
                $msg = "DB Error: " . $stmt->error;
            }
        } else {
            $msg = "Sorry, there was an error uploading your file.";
        }
    }
}
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Upload Document')); ?>
    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <div class="row justify-content-center">
                        <div class="col-md-8">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title">Upload Medical Document</h4>
                                </div>
                                <div class="card-body">
                                    <?php if ($msg): ?>
                                        <div class="alert alert-info"><?php echo $msg; ?></div><?php endif; ?>

                                    <form method="POST" enctype="multipart/form-data">
                                        <?php if ($patient_id): ?>
                                            <div class="mb-3">
                                                <label class="form-label">Patient</label>
                                                <input type="hidden" name="patient_id" value="<?php echo $patient_id; ?>">
                                                <input type="text" class="form-control"
                                                    value="<?php echo htmlspecialchars($p['first_name'] . ' ' . $p['last_name'] . ' (' . $p['patient_number'] . ')'); ?>"
                                                    readonly>
                                            </div>
                                        <?php else: ?>
                                            <div class="mb-3">
                                                <label class="form-label">Patient ID</label>
                                                <input type="number" name="patient_id" class="form-control"
                                                    placeholder="Enter Patient ID" required>
                                            </div>
                                        <?php endif; ?>

                                        <div class="mb-3">
                                            <label class="form-label">Document Title</label>
                                            <input type="text" name="title" class="form-control" required>
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label">Document Type</label>
                                            <select name="doc_type" class="form-select" required>
                                                <option value="CONSULTATION_NOTE">Consultation Note</option>
                                                <option value="PROCEDURE_REPORT">Procedure Report</option>
                                                <option value="TEST_RESULT">Test Result</option>
                                                <option value="IMAGING">Imaging (X-Ray/Scan)</option>
                                                <option value="PRESCRIPTION">Prescription</option>
                                                <option value="REFERRAL">Referral Letter</option>
                                                <option value="OTHER">Other</option>
                                            </select>
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label">File</label>
                                            <input type="file" name="doc_file" class="form-control" required>
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label">Description / Notes</label>
                                            <textarea name="description" class="form-control" rows="3"></textarea>
                                        </div>

                                        <div class="d-grid">
                                            <button type="submit" name="upload" class="btn btn-primary">Upload
                                                Document</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>

</html>