<?php
/**
 * MJPOS — Send Daily Report SMS (standalone, lightweight)
 * Access: /mjpos/public/send_report.php?date=2026-07-16
 * Also used as cron: php send_report.php
 */
require_once __DIR__ . '/../config/config.php';

// Auth check (web request)
if (PHP_SAPI !== 'cli') {
    if (!Auth::check()) {
        header('Location: ' . APP_URL . '/auth/login');
        exit;
    }
    if (!Auth::can('reports.view')) {
        http_response_code(403); die('Forbidden');
    }
}

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

// Get admin phone
$adminPh = setting('admin_report_phone','') ?: setting('admin_reset_phone','');
if (!$adminPh) {
    $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) {
    if (PHP_SAPI === 'cli') { echo "ERROR: No admin phone\n"; exit(1); }
    $_SESSION['flash']['error'][] = 'Admin phone not set. Settings → SMS → Admin Report Phone.';
    header('Location: ' . APP_URL . '/reports/daily?date=' . $date);
    exit;
}

// Daily stats
$sales = Database::fetchOne(
    "SELECT COUNT(*) AS bills,
            COALESCE(SUM(s.total),0) AS total,
            COALESCE(SUM(s.balance),0) AS outstanding,
            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]
);
$cashBal = (float)Database::fetchColumn(
    "SELECT COALESCE(SUM(current_balance),0) FROM finance_accounts WHERE account_type='cash' AND status='active'"
);
$bankBal = (float)Database::fetchColumn(
    "SELECT COALESCE(SUM(current_balance),0) 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);
$due        = (float)($sales['outstanding'] ?? 0);
$expTotal   = (float)($expenses['total']    ?? 0);
$netProfit  = $profit - $expTotal;
$margin     = $salesTotal > 0 ? round($profit / $salesTotal * 100, 1) : 0;
$reportDate = date('d M Y', strtotime($date));
$reportUrl  = APP_URL . '/reports/daily?date=' . $date;

// Build SMS
$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)
     . ($due > 0 ? " | Due: {$sym}" . number_format($due, 2) : '') . "\n"
     . "Cash: {$sym}" . number_format($cashBal, 0)
     . " | Bank: {$sym}" . number_format($bankBal, 0) . "\n"
     . "View: {$reportUrl}";

// Send SMS
$smsOk = false; $smsMsg = 'SMS not enabled';
if (function_exists('curl_init') && setting('sms_enabled','0') === '1') {
    $p = preg_replace('/[\s\-]/','',$adminPh);
    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'   => $msg,
        ]),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 12,
        CURLOPT_SSL_VERIFYPEER => false,
    ]);
    $raw    = curl_exec($ch); curl_close($ch);
    $resp   = $raw ? json_decode($raw,true) : null;
    $smsOk  = $resp['success'] ?? false;
    $smsMsg = $resp['message'] ?? 'No response';
}

// Log
$logDir = __DIR__ . '/../storage/logs';
@mkdir($logDir, 0755, true);
$log = date('Y-m-d H:i:s') . " | {$date} | Bills:{$bills} Sales:{$salesTotal}"
     . " | SMS:" . ($smsOk ? "OK->{$adminPh}" : "FAIL:{$smsMsg}") . "\n";
@file_put_contents($logDir . '/sms_report.log', $log, FILE_APPEND);

if (PHP_SAPI === 'cli') {
    echo $log;
    exit($smsOk ? 0 : 1);
}

// Web redirect
Auth::logAudit(Auth::id(), 'daily_report_sms', 'reports', "SMS {$date}: " . ($smsOk ? 'OK' : $smsMsg));
$_SESSION['flash'][$smsOk?'success':'error'][] = $smsOk
    ? "Report SMS sent to " . substr($adminPh,0,4) . "****" . substr($adminPh,-2)
    : "SMS failed: {$smsMsg}";
header('Location: ' . APP_URL . '/reports/daily?date=' . $date);
exit;