<?php
/**
 * Edit Reminder
 * Update follow-up reminder details
 */

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

requireLogin();

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

// Get case details
$stmt = $pdo->prepare("SELECT c.id, c.patient_name, c.patient_mobile, c.follow_up_date, c.status
                      FROM cases c
                      WHERE c.id = ? AND c.user_id = ?");
$stmt->execute([$reminderId, $userId]);
$case = $stmt->fetch();

if (!$case) {
    header('Location: index.php?error=Reminder not found');
    exit;
}

// Get follow-up notes if any
$stmt = $pdo->prepare("SELECT * FROM follow_ups WHERE case_id = ? ORDER BY created_at DESC LIMIT 1");
$stmt->execute([$reminderId]);
$followUp = $stmt->fetch();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $followUpDate = $_POST['follow_up_date'];
    $caseStatus = $_POST['case_status'];
    $notes = trim($_POST['notes']);
    
    // Update case
    $stmt = $pdo->prepare("UPDATE cases SET follow_up_date = ?, status = ? WHERE id = ? AND user_id = ?");
    $stmt->execute([$followUpDate, $caseStatus, $reminderId, $userId]);
    
    // Update or insert follow-up notes
    if ($followUp) {
        $stmt = $pdo->prepare("UPDATE follow_ups SET follow_up_date = ?, progress = ? WHERE case_id = ?");
        $stmt->execute([$followUpDate, $notes, $reminderId]);
    } else {
        $stmt = $pdo->prepare("INSERT INTO follow_ups (case_id, follow_up_date, progress) VALUES (?, ?, ?)");
        $stmt->execute([$reminderId, $followUpDate, $notes]);
    }
    
    $success = "Reminder updated successfully!";
    
    // Refresh data
    $stmt = $pdo->prepare("SELECT c.id, c.patient_name, c.patient_mobile, c.follow_up_date, c.status
                          FROM cases c WHERE c.id = ? AND c.user_id = ?");
    $stmt->execute([$reminderId, $userId]);
    $case = $stmt->fetch();
    
    $stmt = $pdo->prepare("SELECT * FROM follow_ups WHERE case_id = ? ORDER BY created_at DESC LIMIT 1");
    $stmt->execute([$reminderId]);
    $followUp = $stmt->fetch();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit 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-edit"></i> Edit 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; ?>
                    
                    <div class="alert alert-info">
                        <strong>Patient:</strong> <?php echo escape($case['patient_name']); ?> 
                        (<?php echo $case['patient_mobile']; ?>)
                    </div>
                    
                    <form method="POST">
                        <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 $case['follow_up_date']; ?>" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="case_status" class="form-label">Case Status</label>
                            <select name="case_status" id="case_status" class="form-control">
                                <option value="active" <?php echo $case['status'] == 'active' ? 'selected' : ''; ?>>Active</option>
                                <option value="follow-up" <?php echo $case['status'] == 'follow-up' ? 'selected' : ''; ?>>Follow-up Required</option>
                                <option value="closed" <?php echo $case['status'] == 'closed' ? 'selected' : ''; ?>>Closed</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label for="notes" class="form-label">Notes / Instructions</label>
                            <textarea name="notes" id="notes" class="form-control" rows="5" 
                                      placeholder="Any specific instructions for this follow-up..."><?php echo htmlspecialchars($followUp['progress'] ?? ''); ?></textarea>
                        </div>
                        
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> Update Reminder
                        </button>
                        <a href="index.php" class="btn btn-secondary">Cancel</a>
                        <a href="../cases/view.php?id=<?php echo $reminderId; ?>" class="btn btn-info">
                            <i class="fas fa-eye"></i> View Full Case
                        </a>
                    </form>
                </div>
            </div>
            
            <div class="col-md-4">
                <div class="form-card">
                    <h6><i class="fas fa-history"></i> Reminder History</h6>
                    <hr>
                    <?php
                    $stmt = $pdo->prepare("SELECT * FROM follow_ups WHERE case_id = ? ORDER BY follow_up_date DESC");
                    $stmt->execute([$reminderId]);
                    $history = $stmt->fetchAll();
                    ?>
                    <?php if(empty($history)): ?>
                        <p class="text-muted small">No previous follow-up history</p>
                    <?php else: ?>
                        <div class="small">
                            <?php foreach($history as $h): ?>
                                <div class="border-bottom pb-2 mb-2">
                                    <strong><?php echo date('d-m-Y', strtotime($h['follow_up_date'])); ?></strong>
                                    <p class="mb-0 text-muted"><?php echo substr($h['progress'] ?? 'No notes', 0, 100); ?></p>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
                
                <div class="form-card mt-3">
                    <h6><i class="fas fa-envelope"></i> Send Reminder</h6>
                    <hr>
                    <div class="d-grid gap-2">
                        <a href="send.php?id=<?php echo $reminderId; ?>&type=sms" class="btn btn-primary">
                            <i class="fas fa-sms"></i> Send SMS Reminder
                        </a>
                        <a href="send.php?id=<?php echo $reminderId; ?>&type=email" class="btn btn-success">
                            <i class="fas fa-envelope"></i> Send Email Reminder
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>