<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Autoload PHPMailer via Composer
require '/home/wiselie/public_html/vendor/autoload.php';

// Konfigurasi SMTP untuk email cPanel
$smtpHost = 'mail.wiselie.co.id'; // Host SMTP untuk cPanel
$smtpUsername = 'admin@wiselie.co.id'; // Username SMTP (email cPanel)
$smtpPassword = 'Rnanda123.'; // Password email cPanel
$smtpPort = 465; // Port SMTP untuk SSL
$smtpEncryption = PHPMailer::ENCRYPTION_SMTPS; // Enkripsi SSL

// Fetch current date
$current_date = date('Y-m-d');

// Konfigurasi database
$host = 'localhost';
$user = 'wiselie_nanda';
$password = 'Clemira123';
$database = 'wiselie_inventory';

// Koneksi ke database
$db = new mysqli($host, $user, $password, $database);
if ($db->connect_error) {
    die("Connection failed: " . $db->connect_error);
}

// Fetch total scanned in and scan status counts for the current date
$sql_scan_in = "SELECT COUNT(DISTINCT resi) as total_scan_in FROM awb WHERE DATE(scan_in) = '{$current_date}'";
$result_scan_in = $db->query($sql_scan_in);
$total_scan_in = 0;
if ($row = $result_scan_in->fetch_assoc()) {
    $total_scan_in = $row['total_scan_in'];
}

$sql_scan_status = "SELECT COUNT(DISTINCT resi) as total_scan_status FROM awb WHERE DATE(scan_status) = '{$current_date}'";
$result_scan_status = $db->query($sql_scan_status);
$total_scan_status = 0;
if ($row = $result_scan_status->fetch_assoc()) {
    $total_scan_status = $row['total_scan_status'];
}

// Calculate progress percentage and format to 2 decimal places
$progress_percentage = ($total_scan_in > 0) ? ($total_scan_status / $total_scan_in) * 100 : 0;
$progress_percentage_formatted = number_format($progress_percentage, 2);

// Fetch Top 5 Incoming Orders by Scan In for the current date
$sql_top_incoming = "
    SELECT part_number, SUM(quantity) as total_qty
    FROM awb
    WHERE DATE(scan_in) = '{$current_date}'
    GROUP BY part_number
    ORDER BY total_qty DESC
    LIMIT 5
";
$result_top_incoming = $db->query($sql_top_incoming);

$top_incoming = [];
while ($row = $result_top_incoming->fetch_assoc()) {
    $part_number = $row['part_number'];
    $quantity = $row['total_qty'];

    // Fetch product name
    $sql_product_name = "SELECT name FROM products WHERE part_number = '{$part_number}' LIMIT 1";
    $result_product_name = $db->query($sql_product_name);
    $product_name = $result_product_name->fetch_assoc()['name'];

    $top_incoming[] = [
        'part_number' => $part_number,
        'name' => $product_name,
        'quantity' => $quantity
    ];
}

// Fetch email addresses
$sql_emails = "SELECT email FROM email_list";
$result_emails = $db->query($sql_emails);

$to = [];
while ($row = $result_emails->fetch_assoc()) {
    $to[] = $row['email'];
}

$subject = "Daily Report for {$current_date}";
$message = "
<html>
<head>
    <title>Daily Scan Report</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background: #f9f9f9;
            border: 1px solid #ddd;
            border-radius: 8px;
        }
        h1 {
            color: #333;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        table, th, td {
            border: 1px solid #ddd;
        }
        th, td {
            padding: 12px;
            text-align: center;
        }
        th {
            background-color: #f4f4f4;
        }
        .progress-bar {
            height: 30px;
            background: #4caf50;
            width: {$progress_percentage_formatted}%;
            color: white;
            text-align: center;
            line-height: 30px;
            border-radius: 15px;
        }
    </style>
</head>
<body>
    <div class='container'>
        <h1>Scan Results for {$current_date}</h1>
        <table>
            <thead>
                <tr>
                    <th>Type</th>
                    <th>Total AWB</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Scanned In</td>
                    <td>{$total_scan_in}</td>
                </tr>
                <tr>
                    <td>Scanned Out</td>
                    <td>{$total_scan_status}</td>
                </tr>
            </tbody>
        </table>
        <div class='progress-bar'>{$progress_percentage_formatted}%</div>
        <h2>Top 5 Incoming Orders by Scan In</h2>
        <table>
            <thead>
                <tr>
                    <th>Part Number</th>
                    <th>Name</th>
                    <th>Quantity</th>
                </tr>
            </thead>
            <tbody>
";

foreach ($top_incoming as $incoming) {
    $message .= "
                <tr>
                    <td>{$incoming['part_number']}</td>
                    <td>{$incoming['name']}</td>
                    <td>{$incoming['quantity']}</td>
                </tr>
    ";
}

$message .= "
            </tbody>
        </table>
    </div>
</body>
</html>
";

// Initialize send status
$sendStatus = '';

$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->isSMTP();
    $mail->Host       = $smtpHost;
    $mail->SMTPAuth   = true;
    $mail->Username   = $smtpUsername;
    $mail->Password   = $smtpPassword;
    $mail->SMTPSecure = $smtpEncryption;
    $mail->Port       = $smtpPort;

    //Recipients
    $mail->setFrom($smtpUsername, 'Wiselie Admin');

    // Add each email address separately
    foreach ($to as $email) {
        $mail->addAddress($email);
    }

    //Content
    $mail->isHTML(true);
    $mail->Subject = $subject;
    $mail->Body    = $message;

    $mail->send();
    $sendStatus = 'Pesan telah berhasil dikirim';
} catch (Exception $e) {
    $sendStatus = "Pesan gagal dikirim. Mailer Error: {$mail->ErrorInfo}";
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Send Email Status</title>
</head>
<body>

<h1>Status Pengiriman Email</h1>
<p><?php echo $sendStatus; ?></p>

</body>
</html>
