<?php
require_once '../db.php';

$message = '';
$currentTab = isset($_GET['tab']) ? $_GET['tab'] : 'write';

if($_SERVER['REQUEST_METHOD'] == 'POST') {
    if(isset($_POST['title']) && isset($_POST['description']) && isset($_POST['content'])) {
        $title = trim($_POST['title']);
        $description = trim($_POST['description']);
        $content = trim($_POST['content']);
        
        if(!empty($title) && !empty($description) && !empty($content)) {
            try {
                $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
                $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                
                $stmt = $pdo->prepare("INSERT INTO articles (title, description, content) VALUES (?, ?, ?)");
                $stmt->execute([$title, $description, $content]);
                
                $stmt = $pdo->query("SELECT email FROM newsletter_subscribers");
                $subscribers = $stmt->fetchAll(PDO::FETCH_COLUMN);
                
                if(!empty($subscribers)) {
                    $articleId = $pdo->lastInsertId();
                    $subject = "Nouvel article : " . $title;
                    
                    $emailBody = '
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>' . htmlspecialchars($title) . '</title>
    <style>
        body {
            font-family: "Cabinet Grotesk", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #ffffff;
            color: #121212;
            line-height: 1.6;
        }
        
        .container {
            max-width: 600px;
            margin: 0 auto;
            padding: 40px 20px;
        }
        
        .header {
            text-align: center;
            border-bottom: 1px solid rgba(0, 0, 0, 0.1);
            padding-bottom: 30px;
            margin-bottom: 40px;
        }
        
        .logo {
            font-size: 2rem;
            font-weight: 300;
            letter-spacing: -0.02em;
            margin-bottom: 10px;
        }
        
        .tagline {
            font-size: 0.9rem;
            opacity: 0.6;
            text-transform: uppercase;
            letter-spacing: 0.1em;
        }
        
        .content {
            margin-bottom: 40px;
        }
        
        .greeting {
            font-size: 1.1rem;
            margin-bottom: 20px;
        }
        
        .article-title {
            font-size: 1.8rem;
            font-weight: 300;
            letter-spacing: -0.01em;
            margin: 30px 0 15px 0;
            color: #121212;
        }
        
        .article-description {
            font-size: 1rem;
            opacity: 0.7;
            margin-bottom: 30px;
            line-height: 1.7;
        }
        
        .cta-button {
            display: inline-block;
            background-color: #121212;
            color: #ffffff;
            padding: 15px 30px;
            border-radius: 30px;
            text-decoration: none;
            font-size: 0.9rem;
            font-weight: 300;
            letter-spacing: 0.05em;
            margin: 20px 0;
            transition: opacity 0.2s ease;
        }
        
        .footer {
            border-top: 1px solid rgba(0, 0, 0, 0.1);
            padding-top: 30px;
            text-align: center;
            font-size: 0.8rem;
            opacity: 0.5;
        }
        
        .signature {
            margin-top: 30px;
            font-size: 0.95rem;
        }
        
        @media (prefers-color-scheme: dark) {
            body {
                background-color: #121212;
                color: #f5f5f5;
            }
            
            .header {
                border-color: rgba(255, 255, 255, 0.1);
            }
            
            .article-title {
                color: #f5f5f5;
            }
            
            .cta-button {
                background-color: #f5f5f5;
                color: #121212;
            }
            
            .footer {
                border-color: rgba(255, 255, 255, 0.1);
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <div class="logo">Izhak</div>
            <div class="tagline">Blog & Insights</div>
        </div>
        
        <div class="content">
            <div class="greeting">Hey.</div>
            
            <p>I have published a new article</p>
            
            <div class="article-title">' . htmlspecialchars($title) . '</div>
            <div class="article-description">' . htmlspecialchars($description) . '</div>
            
            <a href="https://izhak.me/view.php?id=' . $articleId . '" class="cta-button">Read that</a>
            
            <div class="signature">
                See you soon,<br>
                <strong>Izhak</strong><br>
            </div>
        </div>
        
        <div class="footer">
            <p>You are receiving this email because you have subscribed my newsletter.</p>
            <p>Designed with a smile. Mail send by the Imators Systems 1.3 version</p>
        </div>
    </div>
</body>
</html>';
                    
                    $headers = "From: izhak@imators.com\r\n";
                    $headers .= "Reply-To: izhak@imators.com\r\n";
                    $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
                    $headers .= "MIME-Version: 1.0\r\n";
                    
                    foreach($subscribers as $email) {
                        mail($email, $subject, $emailBody, $headers);
                    }
                    
                    $message = '<div class="message success">Article publié et envoyé à ' . count($subscribers) . ' abonné(s) !</div>';
                } else {
                    $message = '<div class="message success">Article publié avec succès !</div>';
                }
                
            } catch(PDOException $e) {
                $message = '<div class="message error">Erreur : ' . htmlspecialchars($e->getMessage()) . '</div>';
            }
        } else {
            $message = '<div class="message error">Tous les champs sont obligatoires.</div>';
        }
    }
    
    if(isset($_POST['delete_review'])) {
        $reviewId = intval($_POST['review_id']);
        
        try {
            $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            
            $stmt = $pdo->prepare("DELETE FROM avis WHERE id = ?");
            $stmt->execute([$reviewId]);
            
            $message = '<div class="message success">Review deleted successfully!</div>';
        } catch(PDOException $e) {
            $message = '<div class="message error">Error: ' . htmlspecialchars($e->getMessage()) . '</div>';
        }
    }
    
    if(isset($_POST['toggle_approval'])) {
        $reviewId = intval($_POST['review_id']);
        $newStatus = intval($_POST['new_status']);
        
        try {
            $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            
            $stmt = $pdo->prepare("UPDATE avis SET approved = ? WHERE id = ?");
            $stmt->execute([$newStatus, $reviewId]);
            
            $status = $newStatus ? 'approved' : 'hidden';
            $message = '<div class="message success">Review ' . $status . ' successfully!</div>';
        } catch(PDOException $e) {
            $message = '<div class="message error">Error: ' . htmlspecialchars($e->getMessage()) . '</div>';
        }
    }
}

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    $stmt = $pdo->query("SELECT * FROM avis ORDER BY date_creation DESC");
    $reviews = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
    $message = '<div class="message error">Error loading reviews: ' . htmlspecialchars($e->getMessage()) . '</div>';
    $reviews = [];
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin - Dashboard</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="icon" href="../icon.png" type="image/png">
    <link href="https://api.fontshare.com/v2/css?f[]=cabinet-grotesk@400,500,700,800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <style>
        :root {
            --bg-light: #ffffff;
            --bg-dark: #121212;
            --text-light: #121212;
            --text-dark: #f5f5f5;
            --border-light: rgba(0, 0, 0, 0.1);
            --border-dark: rgba(255, 255, 255, 0.1);
        }

        @media (prefers-color-scheme: dark) {
            body {
                background-color: var(--bg-dark);
                color: var(--text-dark);
            }
            .header-border {
                border-top: 1px solid var(--text-dark);
                border-bottom: 1px solid var(--text-dark);
                background-color: rgba(18, 18, 18, 0.8);
            }
            .border-custom {
                border-color: var(--border-dark);
            }
            .form-input {
                background-color: rgba(255, 255, 255, 0.05);
                border-color: var(--border-dark);
                color: var(--text-dark);
            }
            .review-card {
                background-color: rgba(255, 255, 255, 0.05);
                border-color: var(--border-dark);
            }
            .tab-button.active {
                background-color: var(--text-dark);
                color: var(--bg-dark);
            }
            .tab-button {
                color: var(--text-dark);
            }
        }

        @media (prefers-color-scheme: light) {
            body {
                background-color: var(--bg-light);
                color: var(--text-light);
            }
            .header-border {
                border-top: 1px solid var(--text-light);
                border-bottom: 1px solid var(--text-light);
                background-color: rgba(255, 255, 255, 0.8);
            }
            .border-custom {
                border-color: var(--border-light);
            }
            .form-input {
                background-color: rgba(0, 0, 0, 0.02);
                border-color: var(--border-light);
                color: var(--text-light);
            }
            .review-card {
                background-color: rgba(0, 0, 0, 0.02);
                border-color: var(--border-light);
            }
            .tab-button.active {
                background-color: var(--text-light);
                color: var(--bg-light);
            }
            .tab-button {
                color: var(--text-light);
            }
        }

        body {
            font-family: 'Cabinet Grotesk', sans-serif;
            transition: background-color 0.3s ease, color 0.3s ease;
            margin: 0;
            padding: 0;
        }

        .header-border {
            backdrop-filter: blur(10px);
        }

        @keyframes slideUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .slide-up {
            opacity: 0;
            animation: slideUp 0.6s cubic-bezier(0.4, 0, 0.2, 1) forwards;
        }

        .delay-1 {animation-delay: 0.1s;}
        .delay-2 {animation-delay: 0.2s;}
        .delay-3 {animation-delay: 0.3s;}

        .content-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 2rem;
        }

        .form-container {
            max-width: 800px;
            margin: 0 auto;
        }

        .form-group {
            margin-bottom: 2rem;
        }

        .form-label {
            display: block;
            font-size: 0.9rem;
            font-weight: 300;
            margin-bottom: 0.5rem;
            opacity: 0.7;
        }

        .form-input {
            width: 100%;
            padding: 1rem;
            border: 1px solid;
            border-radius: 0.5rem;
            font-family: 'Cabinet Grotesk', sans-serif;
            font-size: 1rem;
            transition: border-color 0.2s ease;
        }

        .form-input:focus {
            outline: none;
            opacity: 1;
        }

        .form-textarea {
            min-height: 300px;
            resize: vertical;
        }

        .review-card {
            border: 1px solid;
            border-radius: 0.75rem;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            transition: all 0.2s ease;
        }

        .review-card:hover {
            transform: translateY(-2px);
        }

        .stars {
            color: #fbbf24;
        }

        .button-custom {
            background-color: var(--text-light);
            color: var(--bg-light);
            padding: 1rem 2rem;
            border-radius: 2rem;
            font-size: 0.9rem;
            font-weight: 300;
            letter-spacing: 0.05em;
            transition: opacity 0.2s ease;
            text-decoration: none;
            display: inline-block;
            border: none;
            cursor: pointer;
            font-family: 'Cabinet Grotesk', sans-serif;
        }

        @media (prefers-color-scheme: dark) {
            .button-custom {
                background-color: var(--text-dark);
                color: var(--bg-dark);
            }
        }

        .button-custom:hover {
            opacity: 0.8;
        }

        .button-small {
            padding: 0.75rem 1.5rem;
            font-size: 0.85rem;
            margin-right: 0.5rem;
        }

        .button-secondary {
            background-color: transparent;
            color: var(--text-light);
            border: 1px solid var(--border-light);
        }

        @media (prefers-color-scheme: dark) {
            .button-secondary {
                color: var(--text-dark);
                border-color: var(--border-dark);
            }
        }

        .button-danger {
            background-color: #ef4444;
            color: #ffffff;
        }

        .button-success {
            background-color: #22c55e;
            color: #ffffff;
        }

        .button-warning {
            background-color: #f59e0b;
            color: #ffffff;
        }

        .message {
            padding: 1rem;
            border-radius: 0.5rem;
            margin-bottom: 2rem;
            font-size: 0.9rem;
        }

        .message.success {
            background-color: rgba(34, 197, 94, 0.1);
            border: 1px solid rgba(34, 197, 94, 0.3);
            color: #22c55e;
        }

        .message.error {
            background-color: rgba(239, 68, 68, 0.1);
            border: 1px solid rgba(239, 68, 68, 0.3);
            color: #ef4444;
        }

        .tabs {
            display: flex;
            gap: 1rem;
            margin-bottom: 3rem;
            justify-content: center;
            flex-wrap: wrap;
        }

        .tab-button {
            padding: 1rem 2rem;
            border-radius: 2rem;
            font-size: 0.9rem;
            font-weight: 300;
            letter-spacing: 0.05em;
            text-decoration: none;
            transition: all 0.2s ease;
            border: 1px solid var(--border-light);
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }

        @media (prefers-color-scheme: dark) {
            .tab-button {
                border-color: var(--border-dark);
            }
        }

        .tab-button:hover {
            opacity: 0.8;
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1.5rem;
            margin-bottom: 3rem;
        }

        .stat-card {
            text-align: center;
            padding: 1.5rem;
            border: 1px solid;
            border-radius: 0.75rem;
        }

        .review-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1rem;
            flex-wrap: wrap;
            gap: 1rem;
        }

        .review-actions {
            display: flex;
            gap: 0.5rem;
            flex-wrap: wrap;
        }

        .approved-badge {
            background-color: rgba(34, 197, 94, 0.1);
            color: #22c55e;
            padding: 0.25rem 0.75rem;
            border-radius: 1rem;
            font-size: 0.75rem;
            font-weight: 500;
        }

        .hidden-badge {
            background-color: rgba(156, 163, 175, 0.1);
            color: #9ca3af;
            padding: 0.25rem 0.75rem;
            border-radius: 1rem;
            font-size: 0.75rem;
            font-weight: 500;
        }

        .actions {
            display: flex;
            gap: 1rem;
            justify-content: center;
            margin-top: 2rem;
        }

        @media (max-width: 768px) {
            .content-container {
                padding: 1rem;
            }
            
            .review-meta {
                flex-direction: column;
                align-items: flex-start;
            }
            
            .review-actions {
                width: 100%;
            }
            
            .button-custom {
                flex: 1;
                text-align: center;
            }
            
            .actions {
                flex-direction: column;
            }

            .tabs {
                gap: 0.5rem;
            }

            .tab-button {
                padding: 0.75rem 1.5rem;
                font-size: 0.8rem;
            }
        }
    </style>
</head>
<body class="min-h-screen">
    <header class="header-border py-6 sticky top-0 z-50 slide-up">
        <div class="max-width-1200px mx-auto px-6">
            <div class="flex justify-between items-center">
                <h1 class="text-2xl font-light tracking-tight">Izhak</h1>
                <a href="blog.php" class="text-sm font-light hover:opacity-70 transition-opacity">← Back to Blog</a>
            </div>
        </div>
    </header>

    <div class="content-container slide-up delay-1">
        <div class="text-center mb-8">
            <h2 class="text-4xl md:text-5xl font-light tracking-tight mb-4">Admin Dashboard</h2>
            <p class="text-lg font-light opacity-70">Manage your content and reviews</p>
        </div>

        <div class="tabs slide-up delay-2">
            <a href="?tab=write" class="tab-button <?php echo $currentTab === 'write' ? 'active' : ''; ?>">
                <i class="fas fa-pen"></i>
                Write Article
            </a>
            <a href="?tab=reviews" class="tab-button <?php echo $currentTab === 'reviews' ? 'active' : ''; ?>">
                <i class="fas fa-star"></i>
                Reviews Management
            </a>
        </div>

        <?php echo $message; ?>

        <div class="tab-content <?php echo $currentTab === 'write' ? 'active' : ''; ?>" id="write-tab">
            <div class="form-container slide-up delay-3">
                <form method="POST">
                    <div class="form-group">
                        <label for="title" class="form-label">Titre de l'article</label>
                        <input type="text" id="title" name="title" class="form-input" required>
                    </div>

                    <div class="form-group">
                        <label for="description" class="form-label">Description courte</label>
                        <textarea id="description" name="description" class="form-input" rows="3" required placeholder="Un résumé de quelques lignes pour présenter l'article"></textarea>
                    </div>

                    <div class="form-group">
                        <label for="content" class="form-label">Contenu de l'article</label>
                        <textarea id="content" name="content" class="form-input form-textarea" required placeholder="Écris ton article ici..."></textarea>
                    </div>

                    <div class="actions">
                        <button type="submit" class="button-custom">
                            <i class="fas fa-paper-plane mr-2"></i>
                            Publier l'article
                        </button>
                        <a href="blog.php" class="button-custom button-secondary">
                            Annuler
                        </a>
                    </div>
                </form>
            </div>
        </div>

        <div class="tab-content <?php echo $currentTab === 'reviews' ? 'active' : ''; ?>" id="reviews-tab">
            <div class="stats-grid slide-up delay-3">
                <div class="stat-card border-custom">
                    <div class="text-3xl font-light mb-2"><?php echo count($reviews); ?></div>
                    <div class="text-sm opacity-70">Total Reviews</div>
                </div>
                <div class="stat-card border-custom">
                    <div class="text-3xl font-light mb-2"><?php echo count(array_filter($reviews, function($r) { return $r['approved'] == 1; })); ?></div>
                    <div class="text-sm opacity-70">Approved</div>
                </div>
                <div class="stat-card border-custom">
                    <div class="text-3xl font-light mb-2"><?php echo count(array_filter($reviews, function($r) { return $r['approved'] == 0; })); ?></div>
                    <div class="text-sm opacity-70">Hidden</div>
                </div>
                <div class="stat-card border-custom">
                    <div class="text-3xl font-light mb-2">
                        <?php 
                        $total = count($reviews);
                        $sum = array_sum(array_column($reviews, 'note'));
                        echo $total > 0 ? number_format($sum / $total, 1) : '0';
                        ?>
                    </div>
                    <div class="text-sm opacity-70">Average Rating</div>
                </div>
            </div>

            <div class="slide-up delay-3">
                <?php if(empty($reviews)): ?>
                    <div class="text-center py-12">
                        <i class="fas fa-star text-4xl opacity-30 mb-4"></i>
                        <h3 class="text-xl font-light mb-2">No reviews yet</h3>
                        <p class="opacity-70">Customer reviews will appear here when submitted</p>
                    </div>
                <?php else: ?>
                    <?php foreach($reviews as $review): ?>
                        <div class="review-card">
                            <div class="review-meta">
                                <div class="flex items-center gap-4">
                                    <div>
                                        <h3 class="font-medium"><?php echo htmlspecialchars($review['nom']); ?></h3>
                                        <p class="text-sm opacity-70"><?php echo htmlspecialchars($review['email']); ?></p>
                                    </div>
                                    <div class="stars">
                                        <?php for($i = 1; $i <= 5; $i++): ?>
                                            <i class="fas fa-star<?php echo $i <= $review['note'] ? '' : ' opacity-30'; ?>"></i>
                                        <?php endfor; ?>
                                    </div>
                                    <span class="<?php echo $review['approved'] ? 'approved-badge' : 'hidden-badge'; ?>">
                                        <?php echo $review['approved'] ? 'Approved' : 'Hidden'; ?>
                                    </span>
                                </div>
                                <div class="review-actions">
                                    <form method="POST" style="display: inline;">
                                        <input type="hidden" name="review_id" value="<?php echo $review['id']; ?>">
                                        <input type="hidden" name="new_status" value="<?php echo $review['approved'] ? 0 : 1; ?>">
                                        <button type="submit" name="toggle_approval" class="button-custom button-small <?php echo $review['approved'] ? 'button-warning' : 'button-success'; ?>">
                                            <i class="fas fa-<?php echo $review['approved'] ? 'eye-slash' : 'eye'; ?> mr-1"></i>
                                            <?php echo $review['approved'] ? 'Hide' : 'Show'; ?>
                                        </button>
                                    </form>
                                    <form method="POST" style="display: inline;" onsubmit="return confirm('Are you sure you want to delete this review?');">
                                        <input type="hidden" name="review_id" value="<?php echo $review['id']; ?>">
                                        <button type="submit" name="delete_review" class="button-custom button-small button-danger">
                                            <i class="fas fa-trash mr-1"></i>
                                            Delete
                                        </button>
                                    </form>
                                </div>
                            </div>
                            <div class="mb-3">
                                <p class="leading-relaxed"><?php echo nl2br(htmlspecialchars($review['commentaire'])); ?></p>
                            </div>
                            <div class="flex justify-between items-center text-sm opacity-50">
                                <span><?php echo date('d M Y, H:i', strtotime($review['date_creation'])); ?></span>
                                <span>IP: <?php echo htmlspecialchars($review['ip_address']); ?></span>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <footer class="py-8 text-center text-sm font-light opacity-50">
        <p>Designed with a smile.</p>
    </footer>
</body>
</html>