<?php
/**
 * MJPOS Daily Report SMS Sender
 * cPanel Cron: php /home3/mjposliv/public_html/kussiya.mjpos.live/mjpos/public/cron/daily_report.php
 * Schedule: 0 21 * * * (every day at 9:00 PM)
 */

// Security: only allow CLI or with cron key
$cronKey = 'mjpos_cron_' . md5('kussiya_2026_secure');
if (PHP_SAPI !== 'cli') {
    $reqKey = $_GET['key'] ?? '';
    if ($reqKey !== $cronKey) {
        http_response_code(403);
        die('Forbidden');
    }
}

define('MJPOS_CRON', true);
require_once __DIR__ . '/../../config/config.php';

$date     = $_GET['date'] ?? date('Y-m-d');
$sym      = setting('currency_symbol', 'Rs.');
$shopName = setting('shop_name', 'MJPOS');
$adminPh  = setting('admin_report_phone', '') ?: setting('admin_reset_phone', '');

if (!$adminPh) {
    // Find from users table
    $adm = Database::fetchOne(
        "SELECT phone FROM users WHERE role IN ('super_admin','admin','developer')
         AND status='active' AND phone IS NOT NULL AND phone != '' ORDER BY id LIMIT 1"
    );
    $adminPh = $adm['phone'] ?? '';
}

if (!$adminPh) {
    echo "ERROR: No admin phone configured.\n";
    exit(1);
}

// ── Fetch daily stats ────────────────────────────────────
$sales = Database::fetchOne(
    "SELECT COUNT(*) AS bills,
            COALESCE(SUM(s.total),0) AS total,
            COALESCE(SUM(s.balance),0) AS balance,
            COALESCE(SUM(gp.profit),0) AS profit
     FROM sales s
     LEFT JOIN (
         SELECT sale_id, SUM(quantity*(selling_price-cost_price)) AS profit
         FROM sale_items GROUP BY sale_id
     ) gp ON gp.sale_id = s.id
     WHERE DATE(s.sale_date) = ? AND s.status = 'completed'",
    [$date]
);

$expenses = Database::fetchOne(
    "SELECT COALESCE(SUM(amount),0) AS total
     FROM expenses WHERE DATE(expense_date) = ?",
    [$date]
);

$cashBalance = Database::fetchOne(
    "SELECT COALESCE(SUM(current_balance),0) AS total
     FROM finance_accounts WHERE account_type='cash' AND status='active'"
);
$bankBalance = Database::fetchOne(
    "SELECT COALESCE(SUM(current_balance),0) AS total
     FROM finance_accounts WHERE account_type='bank' AND status='active'"
);

$bills       = (int)($sales['bills']      ?? 0);
$salesTotal  = (float)($sales['total']    ?? 0);
$profit      = (float)($sales['profit']   ?? 0);
$outstanding = (float)($sales['balance']  ?? 0);
$expTotal    = (float)($expenses['total'] ?? 0);
$netProfit   = $profit - $expTotal;
$margin      = $salesTotal > 0 ? round($profit / $salesTotal * 100, 1) : 0;
$cash        = (float)($cashBalance['total'] ?? 0);
$bank        = (float)($bankBalance['total'] ?? 0);
$reportDate  = date('d M Y', strtotime($date));
$reportUrl   = APP_URL . '/reports/daily?date=' . $date;

// ── Build SMS message ─────────────────────────────────────
$msg = "{$shopName} | Daily Report {$reportDate}" . "\n"
     . "Bills: {$bills} | Sales: {$sym}" . number_format($salesTotal, 2) . "\n"
     . "Profit: {$sym}" . number_format($profit, 2) . " ({$margin}%)"
     . ($expTotal > 0 ? " | Exp: {$sym}" . number_format($expTotal, 2) : '') . "\n"
     . "Net: {$sym}" . number_format($netProfit, 2)
     . ($outstanding > 0 ? " | Due: {$sym}" . number_format($outstanding, 2) : '') . "\n"
     . "Cash: {$sym}" . number_format($cash, 0)
     . " | Bank: {$sym}" . number_format($bank, 0) . "\n"
     . "View: {$reportUrl}";

// ── Send SMS ──────────────────────────────────────────────
$smsResult = sendSms($adminPh, $msg);

// ── Log result ────────────────────────────────────────────
$logFile = __DIR__ . '/../../storage/logs/cron_sms.log';
@mkdir(dirname($logFile), 0755, true);
$logLine = date('Y-m-d H:i:s') . ' | Date:'.$date
         . ' | Bills:'.$bills . ' | Sales:'.$salesTotal
         . ' | SMS:' . ($smsResult['success'] ? 'OK to '.$adminPh : 'FAIL: '.$smsResult['message'])
         . "\n";
@file_put_contents($logFile, $logLine, FILE_APPEND);

echo $logLine;

// ── SMS Helper ───────────────────────────────────────────
function sendSms(string $phone, string $message): array {
    if (!function_exists('curl_init'))
        return ['success'=>false,'message'=>'cURL not available'];

    $p = preg_replace('/[\s\-]/','',$phone);
    if (preg_match('/^0[0-9]{9}$/',$p))     $p='+94'.substr($p,1);
    elseif (preg_match('/^94\d{9}$/',$p))   $p='+'.$p;
    elseif (preg_match('/^7[0-9]{8}$/',$p)) $p='+94'.$p;

    $ch = curl_init();
    curl_setopt_array($ch,[
        CURLOPT_URL        => rtrim(setting('sms_api_url','https://smslenz.lk/api'),'/').'/send-sms',
        CURLOPT_POST       => true,
        CURLOPT_POSTFIELDS => http_build_query([
            'user_id'   => setting('sms_user_id',''),
            'api_key'   => setting('sms_api_key',''),
            'sender_id' => setting('sms_sender_id','SMSlenzDEMO'),
            'contact'   => $p,
            'message'   => $message,
        ]),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 15,
        CURLOPT_SSL_VERIFYPEER => false,
    ]);
    $raw = curl_exec($ch); curl_close($ch);
    $resp = $raw ? json_decode($raw,true) : null;
    return ['success'=>($resp['success']??false), 'message'=>($resp['message']??'No response')];
}