<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$db_host    = 'localhost';
$db_user    = 'jewellersbd_user';
$db_pass    = 'D2026Berp';
$db_name    = 'jewellersbd_erp';
$backup_dir = '/home/jewellersbd/public_html/erp.jewellersbd.com/backup';
$date       = date('Y-m-d_H-i-s');
$sql_file   = $backup_dir . '/erp_mail_' . $date . '.sql';
$gz_file    = $backup_dir . '/erp_mail_' . $date . '.sql.gz';

$smtp_host  = 'mail.jewellersbd.com';
$smtp_port  = 587;
$smtp_user  = 'backup@jewellersbd.com';
$smtp_pass  = 'backup2026BD';
$mail_to    = 'madabdas2015@gmail.com';

function make_sql($host, $user, $pass, $name, $file) {
    $c = new mysqli($host, $user, $pass, $name);
    if ($c->connect_error) return 'DB Error: ' . $c->connect_error;
    $c->set_charset('utf8mb4');
    $out = "SET FOREIGN_KEY_CHECKS=0;\n\n";
    $r = $c->query("SHOW TABLES");
    while ($row = $r->fetch_array()) {
        $t = $row[0];
        $r2 = $c->query("SHOW CREATE TABLE `$t`");
        $rr = $r2->fetch_assoc();
        $out .= "DROP TABLE IF EXISTS `$t`;\n" . $rr['Create Table'] . ";\n\n";
        $r3 = $c->query("SELECT * FROM `$t`");
        if ($r3 && $r3->num_rows > 0) {
            $out .= "INSERT INTO `$t` VALUES\n";
            $rows = [];
            while ($d = $r3->fetch_row()) {
                $vals = array_map(function($v) use ($c) {
                    return $v === null ? 'NULL' : "'" . $c->real_escape_string($v) . "'";
                }, $d);
                $rows[] = '(' . implode(',', $vals) . ')';
            }
            $out .= implode(",\n", $rows) . ";\n\n";
        }
    }
    $out .= "SET FOREIGN_KEY_CHECKS=1;\n";
    file_put_contents($file, $out);
    $c->close();
    return true;
}

function make_gz($src, $dst) {
    $in  = fopen($src, 'rb');
    $out = gzopen($dst, 'wb9');
    while (!feof($in)) gzwrite($out, fread($in, 65536));
    fclose($in);
    gzclose($out);
    unlink($src);
}

function send_mail($to, $smtp_host, $smtp_port, $smtp_user, $smtp_pass, $subject, $body, $attachment, $filename) {
    $attachment_data = base64_encode(file_get_contents($attachment));
    $boundary = 'ERP_' . time();

    $message  = "From: ERP Backup <$smtp_user>\r\n";
    $message .= "To: $to\r\n";
    $message .= "Subject: $subject\r\n";
    $message .= "MIME-Version: 1.0\r\n";
    $message .= "Content-Type: multipart/mixed; boundary=\"$boundary\"\r\n\r\n";
    $message .= "--$boundary\r\n";
    $message .= "Content-Type: text/plain; charset=utf-8\r\n\r\n";
    $message .= $body . "\r\n\r\n";
    $message .= "--$boundary\r\n";
    $message .= "Content-Type: application/gzip\r\n";
    $message .= "Content-Transfer-Encoding: base64\r\n";
    $message .= "Content-Disposition: attachment; filename=\"$filename\"\r\n\r\n";
    $message .= chunk_split($attachment_data) . "\r\n";
    $message .= "--$boundary--";

    $fp = fopen('php://temp', 'rw');
    fwrite($fp, $message);
    rewind($fp);

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL            => "smtp://$smtp_host:$smtp_port",
        CURLOPT_USE_SSL        => CURLUSESSL_TRY,
        CURLOPT_USERNAME       => $smtp_user,
        CURLOPT_PASSWORD       => $smtp_pass,
        CURLOPT_MAIL_FROM      => $smtp_user,
        CURLOPT_MAIL_RCPT      => [$to],
        CURLOPT_UPLOAD         => true,
        CURLOPT_READDATA       => $fp,
        CURLOPT_INFILESIZE     => strlen($message),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_VERBOSE        => false,
        CURLOPT_TIMEOUT        => 30,
    ]);

    $result = curl_exec($ch);
    $error  = curl_error($ch);
    curl_close($ch);
    fclose($fp);

    return $error ? '❌ Mail Error: ' . $error : '✅ Mail Sent OK';
}

function cleanup($dir) {
    $files = glob($dir . '/erp_mail_*.sql.gz');
    if (count($files) > 7) {
        usort($files, fn($a, $b) => filemtime($a) - filemtime($b));
        foreach (array_slice($files, 0, count($files) - 7) as $f) unlink($f);
    }
}

$log = ["=== Backup Start: " . date('Y-m-d H:i:s') . " ==="];

$r = make_sql($db_host, $db_user, $db_pass, $db_name, $sql_file);
if ($r !== true) { $log[] = $r; die(implode('<br>', $log)); }
$log[] = "✅ DB Dump OK — " . round(filesize($sql_file)/1024, 2) . " KB";

make_gz($sql_file, $gz_file);
$size = round(filesize($gz_file)/1024, 2);
$log[] = "✅ Compressed OK — $size KB";

$subject  = "Jewelry ERP Backup — " . date('Y-m-d H:i');
$mailbody = "দাদা, আজকের ERP backup attached আছে।\n\nDate: " . date('Y-m-d H:i:s') . "\nSize: $size KB\n\n— Auto Backup System";
$filename = basename($gz_file);

$mail_result = send_mail($mail_to, $smtp_host, $smtp_port, $smtp_user, $smtp_pass, $subject, $mailbody, $gz_file, $filename);
$log[] = $mail_result;

cleanup($backup_dir);
$log[] = "✅ Cleanup Done";
$log[] = "=== Backup End: " . date('Y-m-d H:i:s') . " ===";

file_put_contents($backup_dir . '/backup.log', implode("\n", $log) . "\n", FILE_APPEND);
echo '<pre>' . implode("\n", $log) . '</pre>';
?>
