<?php
/**
 * Add Reminder
 * Create a new follow-up reminder for a patient
 */

require_once '../../config/config.php';
require_once '../../includes/functions.php';

requireLogin();

$pdo = getDB();
$userId = $_SESSION['user_id'];
$error = '';
$success = '';
$caseId = (int)($_GET['case_id'] ?? 0);

// Get doctor's cases for dropdown
$stmt = $pdo->prepare("SELECT id, patient_name, patient_mobile, follow_up_date 
                      FROM cases 
                      WHERE user_id = ? 
                      ORDER BY created_at DESC");
$stmt->execute([$userId]);
$cases = $stmt->fetchAll();

// Pre-select case if provided
$selectedCase = null;
if ($caseId) {
    foreach ($cases as $c) {
        if ($c['id'] == $caseId) {
            $selectedCase = $c;
            break;
        }
    }
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $caseId = $_POST['case_id'];
    $followUpDate = $_POST['follow_up_date'];
    $notes = trim($_POST['notes']);
    
    // Update case with follow-up date
    $stmt = $pdo->prepare("UPDATE cases SET follow_up_date = ?, status = 'follow-up' WHERE id = ? AND user_id = ?");
    if ($stmt->execute([$followUpDate, $caseId, $userId])) {
        $success = "Reminder added successfully!";
        
        // Optionally add to reminders table if you want separate reminder tracking
        $stmt = $pdo->prepare("INSERT INTO follow_ups (case_id, follow_up_date, progress) VALUES (?, ?, ?)");
        $stmt->execute([$caseId, $followUpDate, $notes]);
        
        header("refresh:2;url=index.php");
    } else {
        $error = "Failed to add reminder";
    }
}

// Get available SMS/Email templates
$templates = [
    'sms' => "Dear {patient}, this is a reminder for your follow-up appointment on {date}. Please contact us for any queries.",
    'email' => "Dear {patient},\n\nThis is a reminder for your follow-up appointment scheduled on {date}.\n\nPlease contact us if you need to reschedule.\n\nBest regards,\nDr. {doctor}"
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Reminder - <?php echo APP_NAME; ?></title>
    <link href="../../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="../../assets/vendor/fontawesome/css/all.min.css" rel="stylesheet">
    <style>
        body { background: #f0f2f5; }
        .sidebar {
            min-height: 100vh;
            background: linear-gradient(135deg, #1a472a 0%, #0d2818 100%);
            position: fixed;
            left: 0;
            top: 0;
            width: 260px;
        }
        .sidebar .nav-link {
            color: rgba(255,255,255,0.8);
            padding: 12px 20px;
            margin: 5px 10px;
            border-radius: 8px;
        }
        .sidebar .nav-link:hover { background: rgba(255,255,255,0.1); }
        .sidebar .nav-link.active { background: #2ecc71; }
        .sidebar .nav-link i { margin-right: 10px; }
        .main-content { margin-left: 260px; padding: 20px; }
        .top-navbar {
            background: white;
            border-radius: 12px;
            padding: 15px 25px;
            margin-bottom: 25px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        .form-card {
            background: white;
            border-radius: 12px;
            padding: 25px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        @media (max-width: 768px) {
            .sidebar { width: 70px; }
            .sidebar .nav-link span { display: none; }
            .main-content { margin-left: 70px; }
        }
    </style>
</head>
<body>
    <div class="sidebar">
        <div class="text-center py-4"><h4 class="text-white mb-0">🏥</h4></div>
        <nav class="nav flex-column">
            <a class="nav-link" href="../dashboard.php"><i class="fas fa-tachometer-alt"></i> <span>Dashboard</span></a>
            <a class="nav-link" href="../cases/index.php"><i class="fas fa-folder-open"></i> <span>Cases</span></a>
            <a class="nav-link" href="../repertory/index.php"><i class="fas fa-book"></i> <span>Repertory</span></a>
            <a class="nav-link" href="../materia-medica/index.php"><i class="fas fa-capsules"></i> <span>Materia Medica</span></a>
            <a class="nav-link active" href="index.php"><i class="fas fa-bell"></i> <span>Reminders</span></a>
            <a class="nav-link" href="../profile.php"><i class="fas fa-user"></i> <span>Profile</span></a>
            <hr><a class="nav-link" href="../../logout.php"><i class="fas fa-sign-out-alt"></i> <span>Logout</span></a>
        </nav>
    </div>
    
    <div class="main-content">
        <div class="top-navbar">
            <div class="d-flex justify-content-between">
                <h4 class="mb-0"><i class="fas fa-plus"></i> Add Follow-up Reminder</h4>
                <a href="index.php" class="btn btn-secondary btn-sm">Back to Reminders</a>
            </div>
        </div>
        
        <div class="row">
            <div class="col-md-8">
                <div class="form-card">
                    <?php if ($success): ?>
                        <div class="alert alert-success"><?php echo $success; ?></div>
                    <?php endif; ?>
                    
                    <?php if ($error): ?>
                        <div class="alert alert-danger"><?php echo $error; ?></div>
                    <?php endif; ?>
                    
                    <form method="POST">
                        <div class="mb-3">
                            <label for="case_id" class="form-label">Select Patient *</label>
                            <select name="case_id" id="case_id" class="form-control" required>
                                <option value="">-- Select Patient --</option>
                                <?php foreach($cases as $case): ?>
                                    <option value="<?php echo $case['id']; ?>" <?php echo ($selectedCase && $selectedCase['id'] == $case['id']) ? 'selected' : ''; ?>>
                                        <?php echo escape($case['patient_name']); ?> - <?php echo $case['patient_mobile']; ?>
                                        <?php if($case['follow_up_date']): ?>
                                            (Last follow-up: <?php echo date('d-m-Y', strtotime($case['follow_up_date'])); ?>)
                                        <?php endif; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label for="follow_up_date" class="form-label">Follow-up Date *</label>
                            <input type="date" name="follow_up_date" id="follow_up_date" class="form-control" 
                                   value="<?php echo date('Y-m-d', strtotime('+14 days')); ?>" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="notes" class="form-label">Notes (Optional)</label>
                            <textarea name="notes" id="notes" class="form-control" rows="4" 
                                      placeholder="Any specific instructions or notes for this follow-up..."></textarea>
                        </div>
                        
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> Save Reminder
                        </button>
                        <a href="index.php" class="btn btn-secondary">Cancel</a>
                    </form>
                </div>
            </div>
            
            <div class="col-md-4">
                <div class="form-card">
                    <h6><i class="fas fa-info-circle"></i> Information</h6>
                    <hr>
                    <p><strong>Follow-up Scheduling Guidelines:</strong></p>
                    <ul class="small">
                        <li>Acute cases: 3-7 days</li>
                        <li>Chronic cases: 2-4 weeks</li>
                        <li>Maintenance: 1-3 months</li>
                    </ul>
                    
                    <h6 class="mt-3"><i class="fas fa-envelope"></i> Reminder Templates</h6>
                    <div class="small">
                        <p><strong>SMS Template:</strong></p>
                        <code class="d-block bg-light p-2 rounded small"><?php echo $templates['sms']; ?></code>
                        <p class="mt-2"><strong>Email Template:</strong></p>
                        <code class="d-block bg-light p-2 rounded small"><?php echo nl2br($templates['email']); ?></code>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        // Auto-fill patient details when case selected
        $('#case_id').on('change', function() {
            // Can add AJAX to load patient details if needed
        });
    </script>
</body>
</html>