<?php
date_default_timezone_set('Asia/Jakarta');

$RECIPIENTS    = [
//    "6281806427245",
    "6285891169929",
   "6281906371689",
   "628112821007", //Pak joko
    "628999259216", //Dory
    "628170151579", // Pak Andre
    "628119785008", // Pak Larry
    "6281310755777", // Pak Widi
   "6281233334496", // eko
    "6281281032178", //Pak Geofrey
    "6281215566354", //Brayen
    "6281345924155", //Andra
    "6282149411130", //Bara
   "628129942547", //hery
    "628125705585", //Iwan
    "6282122577997" //Bonie
];
$TEMPLATE_NAME = "reporting_odoo_v5_whatsapp";

// ====== Helpers ======
function getAccessToken() {
    $email = "freshfactory@mim.in";
    $pass  = "!Werty123";
    $curl = curl_init('https://mimin-api.mimin.io/whatsapp-api/api/v1/auth/login');
    curl_setopt_array($curl, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode(['email'=>$email,'password'=>$pass]),
        CURLOPT_HTTPHEADER => ['Content-Type: application/json']
    ]);
    $resp = curl_exec($curl);
    curl_close($curl);
    $json = json_decode($resp,true);
    return $json['token'] ?? false;
}

function formatAmount($val) {
    $val = $val ?? 0;
    if ($val >= 1_000_000_000) return round($val/1_000_000_000,1).' M';
    if ($val >= 1_000_000) return round($val/1_000_000,1).' jt';
    if ($val >= 1_000) return round($val/1_000).' rb';
    return (string)$val;
}

function formatNumber($val) {
    return number_format($val ?? 0,0,',','.');
}

// ====== Ambil data Odoo ======
$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_URL => 'https://freshfactory.odoo.com/api/sale/new_walist',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => '{}',
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer bd2a55cb906bfa313fc7d2a3235ba58b4d1425c5',
        'Content-Type: application/json'
    ],
]);
$response = curl_exec($curl);
curl_close($curl);
if (!$response) die("Gagal ambil data dari Odoo");

$data = json_decode($response,true);
$dataSo  = $data['result']['data_so'] ?? [];
$dataKkd = $data['result']['data_kkd'] ?? [];

$kksSummary = $kkdSummary = [];
foreach($dataSo as $item){
    if($item['name']==="PT. Karya Kirana Sempurna") $kksSummary = $item;
    if($item['name']==="PT. Karya Kirana Distribusi") $kkdSummary = $item;
}
if(!$kksSummary || !$kkdSummary) die("Data KKS/KKD tidak ditemukan");

// ====== Build bodyValues 50 slot ======
$bodyValues = [];

// 1-2: tanggal + sumber
$bodyValues[] = date('d M Y', strtotime('-1 day'));

$bodyValues[] = "Odoo";

// 3-18: KKS
$kksFields = [
    ['so_num_now','so_num_mtd'], ['so_amount_now','so_amount_mtd'],
    ['do_num_now','do_num_mtd'], ['do_amount_now','do_amount_mtd'],
    ['si_num_now','si_num_mtd'], ['si_amount_now','si_amount_mtd'],
    ['pay_num_now','pay_num_mtd'], ['pay_amount_now','pay_amount_mtd'],
    ['ret_num_now','ret_num_mtd'], ['ret_amount_now','ret_amount_mtd'],
    ['do_cancel_num_now','do_cancel_num_mtd'], ['do_cancel_amount_now','do_cancel_amount_mtd'],
    ['rc_new_now','rc_new_mtd'], ['ro_new_now','ro_new_mtd'],
    // ['rc_num_all','total_rc_num_mtd'], ['ro_num_all','total_ro_num_mtd']
    ['total_rc_num_mtd','rc_num_all'], ['total_ro_num_mtd','ro_num_all']
];
foreach($kksFields as $f){
    $now = $kksSummary[$f[0]] ?? 0;
    $mtd = $kksSummary[$f[1]] ?? 0;
    $bodyValues[] = strpos($f[0],'amount')!==false 
        ? formatAmount($now)." (".formatAmount($mtd).")"
        : formatNumber($now)." (".formatNumber($mtd).")";
}

// 19-50: KKD + breakdown cabang
$kkdFields = $kksFields; // sama field names
$kkdBranches = $dataKkd;

foreach($kkdFields as $idx=>$f){
    $now = $kkdSummary[$f[0]] ?? 0;
    $mtd = $kkdSummary[$f[1]] ?? 0;

    // simpan summary KKD
    $bodyValues[] = strpos($f[0],'amount')!==false 
        ? formatAmount($now)." (".formatAmount($mtd).")"
        //? formatAmount($mtd)." (".formatAmount($now).")"
        : formatNumber($now)." (".formatNumber($mtd).")";
        //: formatNumber($mtd)." (".formatNumber($now).")";

    // untuk field yang perlu breakdown cabang: SO#, SO Rp, New RO#, Total RO#
    if(in_array($idx,[0,1,13,15])){
        foreach($kkdBranches as $b){
			// Skip KGQUA
        if(($b['wh_name'] ?? '') === 'KGQUA') continue;
		
            $branchName = preg_replace('/^KG/', '', $b['wh_name']); // hapus prefix 'KG' kalau ada
            $bNow = $b[$f[0]] ?? 0;
            $bMtd = $b[$f[1]] ?? 0;
            $bodyValues[] = $branchName . ' ' . 
                (strpos($f[0],'amount')!==false 
                    ? formatAmount($bNow)." (".formatAmount($bMtd).")" 
                    : formatNumber($bNow)." (".formatNumber($bMtd).")");
        }
    }
}


// ====== Kirim WhatsApp via JSON body positional ======
$token = getAccessToken();
if($token){
    foreach($RECIPIENTS as $phone){
        $data = [
            "name"=>$TEMPLATE_NAME,
            "parameter_format"=>"POSITIONAL",
            "phone"=>$phone,
            "category"=>"UTILITY",
            "allow_category_change"=>true,
            "language"=>"id",
            "components"=>[[
                "type"=>"BODY",
                "text"=>"Tim KKS,\nBerikut laporan kegiatan Kemarin (& MTD) tgl *{{1}}* ({{2}})\n\n*KKS*:\n01. SO #  : {{3}}\n02. SO Rp : {{4}}\n03. DO #  : {{5}}\n04. DO Rp : {{6}}\n05. SI #  : {{7}}\n06. SI Rp : {{8}}\n07. Payment # : {{9}}\n08. Payment Rp : {{10}}\n09. Return # : {{11}}\n10. Return Rp : {{12}}\n11. DO Cancel # : {{13}}\n12. DO Cancel Rp : {{14}}\n13. New RC # : {{15}}\n14. New RO # : {{16}}\n15. Total RC # : {{17}}\n16. Total RO # : {{18}}\n\n*KKD*:\n01. SO # : {{19}}\n    1a. {{20}}\n    1b. {{21}}\n    1c. {{22}}\n    1d. {{23}}\n02. SO Rp : {{24}}\n    2a. {{25}}\n    2b. {{26}}\n    2c. {{27}}\n    2d. {{28}}\n03. DO # : {{29}}\n04. DO Rp : {{30}}\n05. SI # : {{31}}\n06. SI Rp : {{32}}\n07. Payment # : {{33}}\n08. Payment Rp : {{34}}\n09. Return # : {{35}}\n10. Return Rp : {{36}}\n11. DO Cancel # : {{37}}\n12. DO Cancel Rp : {{38}}\n13. New RC # : {{39}}\n14. New RO # : {{40}}\n    14a. {{41}}\n    14b. {{42}}\n    14c. {{43}}\n    14d. {{44}}\n15. Total RC #: {{45}}\n16. Total RO #: {{46}}\n    16a. {{47}}\n    16b. {{48}}\n    16c. {{49}}\n    16d. {{50}}\n\nKKR --> Next Report",
                "example"=>["body_text"=>[$bodyValues]]
            ]]
        ];

        $ch = curl_init('https://mimin-api.mimin.io/whatsapp-api/api/v1/whatsapp-dynamic/send-waba-template');
        curl_setopt_array($ch,[
            CURLOPT_RETURNTRANSFER=>true,
            CURLOPT_POST=>true,
            CURLOPT_HTTPHEADER=>['Content-Type: application/json',"Authorization: Bearer $token"],
            CURLOPT_POSTFIELDS=>json_encode($data,JSON_UNESCAPED_UNICODE)
        ]);
        $resp = curl_exec($ch);
        curl_close($ch);
        echo "Sent to $phone. Response: $resp\n";
    }
}else{
    echo "❌ Failed to retrieve access token.\n";
}
