<?php
/**
 * Bookmark Remedies
 * Save favorite remedies for quick access
 */

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

requireLogin();

$pdo = getDB();
$userId = $_SESSION['user_id'];
$action = $_GET['action'] ?? $_POST['action'] ?? '';
$remedyId = (int)($_GET['remedy_id'] ?? $_POST['remedy_id'] ?? 0);

// Create bookmarks table if not exists
$pdo->exec("CREATE TABLE IF NOT EXISTS remedy_bookmarks (
    id INT PRIMARY KEY AUTO_INCREMENT,
    user_id INT NOT NULL,
    remedy_id INT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    FOREIGN KEY (remedy_id) REFERENCES remedies(id) ON DELETE CASCADE,
    UNIQUE KEY unique_bookmark (user_id, remedy_id)
)");

// Handle AJAX requests
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    header('Content-Type: application/json');
    
    if ($action == 'add') {
        $stmt = $pdo->prepare("INSERT IGNORE INTO remedy_bookmarks (user_id, remedy_id) VALUES (?, ?)");
        $stmt->execute([$userId, $remedyId]);
        echo json_encode(['success' => true]);
        
    } elseif ($action == 'remove') {
        $stmt = $pdo->prepare("DELETE FROM remedy_bookmarks WHERE user_id = ? AND remedy_id = ?");
        $stmt->execute([$userId, $remedyId]);
        echo json_encode(['success' => true]);
        
    } elseif ($action == 'toggle') {
        $stmt = $pdo->prepare("SELECT id FROM remedy_bookmarks WHERE user_id = ? AND remedy_id = ?");
        $stmt->execute([$userId, $remedyId]);
        if ($stmt->fetch()) {
            $stmt = $pdo->prepare("DELETE FROM remedy_bookmarks WHERE user_id = ? AND remedy_id = ?");
            $stmt->execute([$userId, $remedyId]);
            echo json_encode(['success' => true, 'bookmarked' => false]);
        } else {
            $stmt = $pdo->prepare("INSERT INTO remedy_bookmarks (user_id, remedy_id) VALUES (?, ?)");
            $stmt->execute([$userId, $remedyId]);
            echo json_encode(['success' => true, 'bookmarked' => true]);
        }
    }
    exit;
}

// Handle deletion from page
if ($action == 'delete' && $remedyId) {
    $stmt = $pdo->prepare("DELETE FROM remedy_bookmarks WHERE user_id = ? AND remedy_id = ?");
    $stmt->execute([$userId, $remedyId]);
    header('Location: bookmark.php?msg=Removed from bookmarks');
    exit;
}

// Get bookmarked remedies
$stmt = $pdo->prepare("SELECT r.*, 
                      (SELECT COUNT(*) FROM rubric_remedy WHERE remedy_id = r.id) as rubric_count,
                      (SELECT COUNT(*) FROM cases WHERE prescribed_remedy_id = r.id) as prescription_count,
                      b.created_at as bookmarked_date
                      FROM remedy_bookmarks b
                      JOIN remedies r ON b.remedy_id = r.id
                      WHERE b.user_id = ?
                      ORDER BY b.created_at DESC");
$stmt->execute([$userId]);
$bookmarks = $stmt->fetchAll();

// Get bookmark statistics
$totalBookmarks = count($bookmarks);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Bookmarks - Materia Medica</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;
            transition: all 0.3s;
        }
        .sidebar .nav-link:hover { background: rgba(255,255,255,0.1); transform: translateX(5px); }
        .sidebar .nav-link.active { background: #2ecc71; color: white; }
        .sidebar .nav-link i { margin-right: 10px; width: 20px; }
        .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);
        }
        .bookmark-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            transition: all 0.2s;
        }
        .bookmark-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .stats-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            text-align: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        .stats-number { font-size: 32px; font-weight: bold; }
        @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 active" href="index.php"><i class="fas fa-capsules"></i> <span>Materia Medica</span></a>
            <a class="nav-link" href="bookmark.php"><i class="fas fa-bookmark"></i> <span>Bookmarks</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-bookmark"></i> My Bookmarked Remedies</h4>
                <a href="index.php" class="btn btn-secondary btn-sm">
                    <i class="fas fa-arrow-left"></i> Browse All
                </a>
            </div>
        </div>
        
        <?php if(isset($_GET['msg'])): ?>
            <div class="alert alert-success alert-dismissible fade show">
                <?php echo $_GET['msg']; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <div class="row">
            <div class="col-md-9">
                <?php if(empty($bookmarks)): ?>
                    <div class="stats-card">
                        <div class="text-center text-muted py-5">
                            <i class="fas fa-bookmark fa-3x mb-3"></i>
                            <p>You haven't bookmarked any remedies yet.</p>
                            <a href="index.php" class="btn btn-primary">Browse Remedies</a>
                        </div>
                    </div>
                <?php else: ?>
                    <?php foreach($bookmarks as $remedy): ?>
                        <div class="bookmark-card">
                            <div class="d-flex justify-content-between align-items-start">
                                <div>
                                    <h5>
                                        <a href="view.php?id=<?php echo $remedy['id']; ?>" class="text-decoration-none">
                                            <?php echo escape($remedy['name']); ?>
                                        </a>
                                        <?php if($remedy['abbreviation']): ?>
                                            <small class="text-muted">(<?php echo escape($remedy['abbreviation']); ?>)</small>
                                        <?php endif; ?>
                                    </h5>
                                    <div class="mt-1">
                                        <span class="badge bg-primary"><?php echo $remedy['rubric_count']; ?> rubrics</span>
                                        <span class="badge bg-success"><?php echo $remedy['prescription_count']; ?> prescriptions</span>
                                        <span class="badge bg-secondary">
                                            <i class="far fa-clock"></i> Bookmarked: <?php echo date('d-m-Y', strtotime($remedy['bookmarked_date'])); ?>
                                        </span>
                                    </div>
                                    <?php if($remedy['materia_medica_text']): ?>
                                        <p class="mt-2 small text-muted">
                                            <?php echo truncate(strip_tags($remedy['materia_medica_text']), 150); ?>
                                        </p>
                                    <?php endif; ?>
                                </div>
                                <div class="dropdown">
                                    <button class="btn btn-sm btn-outline-secondary" data-bs-toggle="dropdown">
                                        <i class="fas fa-ellipsis-v"></i>
                                    </button>
                                    <ul class="dropdown-menu dropdown-menu-end">
                                        <li><a class="dropdown-item" href="view.php?id=<?php echo $remedy['id']; ?>">
                                            <i class="fas fa-eye"></i> View Details</a>
                                        </li>
                                        <li><a class="dropdown-item" href="compare.php?remedy=<?php echo $remedy['id']; ?>">
                                            <i class="fas fa-chart-line"></i> Compare</a>
                                        </li>
                                        <li><a class="dropdown-item" href="../cases/new.php?remedy=<?php echo $remedy['id']; ?>">
                                            <i class="fas fa-plus-circle"></i> New Case</a>
                                        </li>
                                        <li><hr class="dropdown-divider"></li>
                                        <li><a class="dropdown-item text-danger" href="?action=delete&remedy_id=<?php echo $remedy['id']; ?>" 
                                               onclick="return confirm('Remove from bookmarks?')">
                                            <i class="fas fa-trash"></i> Remove</a>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
            
            <div class="col-md-3">
                <!-- Statistics -->
                <div class="stats-card">
                    <div class="stats-number"><?php echo $totalBookmarks; ?></div>
                    <div class="text-muted">Bookmarked Remedies</div>
                </div>
                
                <!-- Quick Links -->
                <div class="stats-card">
                    <h6><i class="fas fa-link"></i> Quick Links</h6>
                    <div class="mt-2">
                        <a href="index.php" class="d-block mb-2">
                            <i class="fas fa-list"></i> Browse All Remedies
                        </a>
                        <a href="search.php" class="d-block mb-2">
                            <i class="fas fa-search"></i> Advanced Search
                        </a>
                        <a href="compare.php" class="d-block">
                            <i class="fas fa-chart-line"></i> Compare Remedies
                        </a>
                    </div>
                </div>
                
                <!-- Tip -->
                <div class="stats-card">
                    <h6><i class="fas fa-lightbulb"></i> Tip</h6>
                    <p class="small text-muted mb-0">
                        Bookmark your frequently used remedies for quick access. 
                        Click the star icon on any remedy page to bookmark it.
                    </p>
                </div>
            </div>
        </div>
    </div>
    
    <script src="../../assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html>