<?php
// admin/email_compose.php
// ============================================================
// AKTIFKAN ERROR REPORTING
// ============================================================
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
require_once 'config.php';
require_once 'email_functions.php';
date_default_timezone_set('Asia/Jakarta');

// ============================================================
// CEK LOGIN - TAMBAHKAN DEBUG
// ============================================================
if (!isset($_SESSION['username'])) {
    // Jika tidak login, redirect ke login
    header("Location: login.php");
    exit();
}

// ============================================================
// KONEKSI DATABASE
// ============================================================
try {
    $db = new PDO('mysql:host=localhost;dbname=erniinrk_solo', 'erniinrk_solo', 'Kelentit123@');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

// ============================================================
// PROSES KIRIM EMAIL
// ============================================================
$success = null;
$error = null;

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $to = $_POST['to'] ?? '';
    $subject = $_POST['subject'] ?? '';
    $message = $_POST['message'] ?? '';
    
    if (empty($to) || empty($subject) || empty($message)) {
        $error = "Semua field harus diisi!";
    } else {
        // Kirim email
        $result = sendEmail($to, $subject, $message);
        
        if ($result['success']) {
            // Simpan ke database
            try {
                $stmt = $db->prepare("
                    INSERT INTO email_messages (subject, sender, recipient, message, status, is_incoming)
                    VALUES (?, ?, ?, ?, 'read', 0)
                ");
                $stmt->execute([$subject, SMTP_FROM_EMAIL, $to, $message]);
                $success = "Email berhasil dikirim ke " . htmlspecialchars($to);
            } catch (PDOException $e) {
                $error = "Email terkirim tapi gagal disimpan: " . $e->getMessage();
            }
        } else {
            $error = $result['error'];
        }
    }
}

// ============================================================
// AMBIL JUMLAH EMAIL UNREAD UNTUK BADGE
// ============================================================
$unreadStmt = $db->prepare("SELECT COUNT(*) as unread FROM email_messages WHERE status = 'unread' AND is_incoming = 1");
$unreadStmt->execute();
$unreadCount = $unreadStmt->fetch(PDO::FETCH_ASSOC)['unread'];
?>
<!DOCTYPE html>
<html>
<head>
    <title>Jago Hongkong - Compose Email</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.1/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        #sidebar {
            width: 250px;
            background: linear-gradient(to bottom, #343a40, #2c3136);
            color: white;
            min-height: 100vh;
            padding-top: 1rem;
            transition: all 0.3s;
            box-shadow: 2px 0 10px rgba(0,0,0,0.1);
            position: fixed;
            left: 0;
            top: 0;
            height: 100%;
        }

        #sidebar a {
            color: rgba(255,255,255,0.8);
            display: block;
            padding: 12px 20px;
            text-decoration: none;
            transition: all 0.3s;
            border-left: 3px solid transparent;
        }

        #sidebar a:hover, #sidebar a.active {
            background: rgba(255,255,255,0.1);
            color: white;
            border-left: 3px solid #007bff;
        }

        #sidebar a i {
            width: 20px;
            margin-right: 10px;
            display: inline-block;
        }

        .main-content {
            margin-left: 250px;
            padding: 20px;
        }
    </style>
</head>
<body>
<?php include 'navbar.php'; ?>

    <!-- Main Content -->
    <div class="main-content">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h2><i class="fas fa-pen mr-2"></i>Compose New Email</h2>
                <p class="mb-0">Kirim email baru ke customer</p>
            </div>
            <div>
                <a href="email.php" class="btn btn-secondary">
                    <i class="fas fa-arrow-left mr-2"></i>Back to Inbox
                </a>
            </div>
        </div>

        <div class="card">
            <div class="card-header bg-dark text-white">
                <h5 class="mb-0"><i class="fas fa-envelope mr-2"></i>Compose Email</h5>
            </div>
            <div class="card-body">
                <?php if (isset($success)): ?>
                    <div class="alert alert-success alert-dismissible fade show">
                        <i class="fas fa-check-circle mr-2"></i><?= $success ?>
                        <button type="button" class="close" data-dismiss="alert">&times;</button>
                    </div>
                <?php endif; ?>
                
                <?php if (isset($error)): ?>
                    <div class="alert alert-danger alert-dismissible fade show">
                        <i class="fas fa-exclamation-circle mr-2"></i><?= $error ?>
                        <button type="button" class="close" data-dismiss="alert">&times;</button>
                    </div>
                <?php endif; ?>
                
                <form method="POST" action="">
                    <div class="form-group">
                        <label><strong>To <span class="text-danger">*</span></strong></label>
                        <input type="email" class="form-control" name="to" placeholder="customer@email.com" required>
                    </div>
                    
                    <div class="form-group">
                        <label><strong>Subject <span class="text-danger">*</span></strong></label>
                        <input type="text" class="form-control" name="subject" placeholder="Subject email" required>
                    </div>
                    
                    <div class="form-group">
                        <label><strong>Message <span class="text-danger">*</span></strong></label>
                        <textarea class="form-control" name="message" rows="10" placeholder="Tulis pesan email..." required></textarea>
                    </div>
                    
                    <div class="form-group">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-paper-plane mr-2"></i>Send Email
                        </button>
                        <a href="email.php" class="btn btn-secondary">Cancel</a>
                    </div>
                </form>
            </div>
        </div>
        
        <div class="card mt-4">
            <div class="card-header bg-light">
                <small class="text-muted"><i class="fas fa-info-circle mr-2"></i>Informasi</small>
            </div>
            <div class="card-body">
                <small>
                    <strong>Pengirim:</strong> <?= SMTP_FROM_EMAIL ?><br>
                    <strong>Nama Pengirim:</strong> <?= SMTP_FROM_NAME ?><br>
                    <strong>Server SMTP:</strong> <?= SMTP_HOST ?> (Port <?= SMTP_PORT ?>)
                </small>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.4/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>