<?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';
$key_file   = '/home/jewellersbd/public_html/erp.jewellersbd.com/backup/jewelerserp-backup-1c40222356ae.json';
$folder_id  = '1jl0K1bPbwrMgaandZYqVCk0SCfcb-bVP';
$date       = date('Y-m-d_H-i-s');
$sql_file   = $backup_dir . '/erp_gdrive_' . $date . '.sql';
$gz_file    = $backup_dir . '/erp_gdrive_' . $date . '.sql.gz';

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 b64u($d) {
    return rtrim(strtr(base64_encode($d), '+/', '-_'), '=');
}

function get_token($key) {
    $now = time();
    $h = b64u(json_encode(['alg' => 'RS256', 'typ' => 'JWT']));
    $p = b64u(json_encode([
        'iss'   => $key['client_email'],
        'scope' => 'https://www.googleapis.com/auth/drive.file',
        'aud'   => 'https://oauth2.googleapis.com/token',
        'exp'   => $now + 3600,
        'iat'   => $now
    ]));
    openssl_sign($h . '.' . $p, $sig, $key['private_key'], 'SHA256');
    $jwt = $h . '.' . $p . '.' . b64u($sig);
    $ch = curl_init('https://oauth2.googleapis.com/token');
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POSTFIELDS     => http_build_query([
            'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
            'assertion'  => $jwt
        ])
    ]);
    $res = json_decode(curl_exec($ch), true);
    curl_close($ch);
    return $res['access_token'] ?? null;
}

function upload($gz, $folder, $keyfile) {
    $key   = json_decode(file_get_contents($keyfile), true);
    $token = get_token($key);
    if (!$token) return '❌ Token failed';
    $meta  = json_encode(['name' => basename($gz), 'parents' => [$folder]]);
    $bnd   = 'ERP_BND_' . time();
    $body  = "--$bnd\r\nContent-Type: application/json\r\n\r\n$meta\r\n"
           . "--$bnd\r\nContent-Type: application/gzip\r\n\r\n"
           . file_get_contents($gz) . "\r\n--$bnd--";
    $ch = curl_init('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&supportsAllDrives=true');
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POSTFIELDS     => $body,
        CURLOPT_HTTPHEADER     => [
            'Authorization: Bearer ' . $token,
            'Content-Type: multipart/related; boundary=' . $bnd,
            'Content-Length: ' . strlen($body)
        ]
    ]);
    $res = curl_exec($ch);
    curl_close($ch);
    return $res;
}

function cleanup($dir) {
    $files = glob($dir . '/erp_gdrive_*.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);
$log[] = "✅ Compressed OK — " . round(filesize($gz_file)/1024, 2) . " KB";

$up   = upload($gz_file, $folder_id, $key_file);
$data = json_decode($up, true);
$log[] = isset($data['id'])
    ? "✅ Google Drive Upload সফল! File: " . $data['name']
    : "❌ Upload Failed: " . $up;

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>';
?>
