<?php
/**
 * Выгрузка статистики по дням в Excel (.xlsx)
 * Параметры: cab=<client_id>&from=YYYY-MM-DD&to=YYYY-MM-DD
 * Доступ: админ — любой кабинет; клиент — только свои.
 */
declare(strict_types=1);
session_start();

function db_main(): PDO {
    static $pdo = null;
    if ($pdo === null) {
        $pdo = new PDO('sqlite:' . __DIR__ . '/data.db', null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_TIMEOUT => 30]);
    }
    return $pdo;
}
function db_users(): PDO {
    static $pdo = null;
    if ($pdo === null) {
        $pdo = new PDO('sqlite:' . __DIR__ . '/users.db', null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_TIMEOUT => 30]);
    }
    return $pdo;
}

$me = $_SESSION['user'] ?? null;
if (!$me) die('Доступ запрещён');
$is_admin = $me['role'] === 'admin';

$cab  = (int)($_GET['cab'] ?? 0);
$from = $_GET['from'] ?? '';
$to   = $_GET['to'] ?? '';
if ($cab <= 0 || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $from) || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $to) || $from > $to) {
    die('Неверные параметры');
}

$db = db_main();

// права: админ — любой, клиент — только свои кабинеты
if (!$is_admin) {
    $mine = $me['client_ids'] ?? [];
    if (!in_array($cab, $mine)) die('Доступ запрещён');
}

$client = $db->prepare('SELECT name, note FROM clients WHERE client_id = ?');
$client->execute([$cab]);
$cl = $client->fetch(PDO::FETCH_ASSOC);
if (!$cl) die('Кабинет не найден');

$rows = $db->prepare("SELECT date, SUM(cost) AS cost, SUM(leads) AS leads
    FROM daily_stats
    WHERE campaign_id IN (SELECT campaign_id FROM campaigns WHERE client_id = ?)
      AND date BETWEEN ? AND ?
    GROUP BY date ORDER BY date");
$rows->execute([$cab, $from, $to]);
$rows = $rows->fetchAll(PDO::FETCH_ASSOC);

$tcost = 0; $tleads = 0;
foreach ($rows as $r) { $tcost += (float)$r['cost']; $tleads += (int)$r['leads']; }

/* ── сборка .xlsx ─────────────────────────────────────── */
function xlsx_escape(string $s): string {
    return htmlspecialchars($s, ENT_XML1 | ENT_QUOTES, 'UTF-8');
}

$header = '<row r="1">'
    . '<c r="A1" t="inlineStr" s="2"><is><t>' . xlsx_escape($cl['name'] . ' (' . $cl['note'] . ') · ' . date('d.m.Y', strtotime($from)) . ' — ' . date('d.m.Y', strtotime($to))) . '</t></is></c>'
    . '<c r="B1" s="2"/><c r="C1" s="2"/><c r="D1" s="2"/></row>';

$head = '<row r="2">'
    . '<c r="A2" t="inlineStr" s="2"><is><t>Дата</t></is></c>'
    . '<c r="B2" t="inlineStr" s="2"><is><t>Расход</t></is></c>'
    . '<c r="C2" t="inlineStr" s="2"><is><t>Заявки</t></is></c>'
    . '<c r="D2" t="inlineStr" s="2"><is><t>CPL</t></is></c></row>';

$total = '<row r="3">'
    . '<c r="A3" t="inlineStr" s="2"><is><t>ИТОГО</t></is></c>'
    . '<c r="B3" s="3"><v>' . round($tcost, 2) . '</v></c>'
    . '<c r="C3" s="3"><v>' . (int)$tleads . '</v></c>'
    . '<c r="D3" s="3"><v>' . ($tleads > 0 ? round($tcost / $tleads, 2) : 0) . '</v></c></row>';

$body = '';
$r = 4;
foreach (array_reverse($rows) as $row) {
    $cost = (float)$row['cost'];
    $leads = (int)$row['leads'];
    $body .= '<row r="' . $r . '">'
        . '<c r="A' . $r . '" t="inlineStr" s="0"><is><t>' . xlsx_escape(date('d.m.Y', strtotime($row['date']))) . '</t></is></c>'
        . '<c r="B' . $r . '" s="1"><v>' . round($cost, 2) . '</v></c>'
        . '<c r="C' . $r . '" s="1"><v>' . $leads . '</v></c>'
        . '<c r="D' . $r . '" s="1"><v>' . ($leads > 0 ? round($cost / $leads, 2) : 0) . '</v></c></row>';
    $r++;
}

$sheet_xml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
    . '<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
    . '<sheetViews><sheetView workbookViewId="0"/></sheetViews>'
    . '<sheetFormatPr defaultRowHeight="15"/>'
    . '<cols><col min="1" max="1" width="16"/><col min="2" max="2" width="14"/><col min="3" max="3" width="10"/><col min="4" max="4" width="12"/></cols>'
    . '<sheetData>' . $header . $head . $total . $body . '</sheetData>'
    . '</worksheet>';

$styles_xml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
    . '<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
    . '<numFmts count="1"><numFmt numFmtId="164" formatCode="#,##0.00"/></numFmts>'
    . '<fonts count="2">'
    . '<font><sz val="11"/><name val="Calibri"/></font>'
    . '<font><b/><sz val="11"/><name val="Calibri"/></font>'
    . '</fonts>'
    . '<fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills>'
    . '<borders count="2">'
    . '<border><left/><right/><top/><bottom/><diagonal/></border>'
    . '<border>'
    . '<left style="thin"><color rgb="FF444444"/></left>'
    . '<right style="thin"><color rgb="FF444444"/></right>'
    . '<top style="thin"><color rgb="FF444444"/></top>'
    . '<bottom style="thin"><color rgb="FF444444"/></bottom>'
    . '<diagonal/>'
    . '</border>'
    . '</borders>'
    . '<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>'
    . '<cellXfs count="4">'
    . '<xf numFmtId="0" fontId="0" fillId="0" borderId="1" xfId="0"/>'
    . '<xf numFmtId="164" fontId="0" fillId="0" borderId="1" applyNumberFormat="1" xfId="0"/>'
    . '<xf numFmtId="0" fontId="1" fillId="0" borderId="1" xfId="0"/>'
    . '<xf numFmtId="164" fontId="1" fillId="0" borderId="1" applyNumberFormat="1" xfId="0"/>'
    . '</cellXfs>'
    . '</styleSheet>';

$workbook_xml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
    . '<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">'
    . '<sheets><sheet name="Статистика" sheetId="1" r:id="rId1"/></sheets>'
    . '</workbook>';

$content_types = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
    . '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'
    . '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>'
    . '<Default Extension="xml" ContentType="application/xml"/>'
    . '<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>'
    . '<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>'
    . '<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>'
    . '</Types>';

$rels = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
    . '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
    . '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>'
    . '</Relationships>';

$wb_rels = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
    . '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
    . '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>'
    . '<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>'
    . '</Relationships>';

$zip = new ZipArchive();
$tmp = tempnam(sys_get_temp_dir(), 'xlsx');
if ($zip->open($tmp, ZipArchive::OVERWRITE) !== true) die('Ошибка создания файла');
$zip->addFromString('[Content_Types].xml', $content_types);
$zip->addFromString('_rels/.rels', $rels);
$zip->addFromString('xl/workbook.xml', $workbook_xml);
$zip->addFromString('xl/_rels/workbook.xml.rels', $wb_rels);
$zip->addFromString('xl/worksheets/sheet1.xml', $sheet_xml);
$zip->addFromString('xl/styles.xml', $styles_xml);
$zip->close();

$fname = 'stats_' . $cab . '_' . $from . '_' . $to . '.xlsx';
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="' . $fname . '"');
header('Content-Length: ' . filesize($tmp));
readfile($tmp);
unlink($tmp);
