<?php
session_start(['read_and_close' => true]);
require '../../includes/db.php';

$comp_id = $_GET['comp_id'] ?? 0;
$user_id = $_SESSION['user_id'];

session_write_close();

/* =========================================
   DAILY SALES
========================================= */
$sql1 = "
SELECT 
    DATE(t_date) as date,
    SUM(t_debit) as amount

FROM transactions

WHERE co_id = :comp_id
AND t_status = 'Confirmed'
AND t_type = 'DEL'
AND t_copy = 'D'

AND MONTH(t_date) = MONTH(CURRENT_DATE)
AND YEAR(t_date) = YEAR(CURRENT_DATE)

GROUP BY DATE(t_date)
ORDER BY DATE(t_date)
";

$stmt1 = $pdo->prepare($sql1);

$stmt1->execute([
    'comp_id' => $comp_id
]);

$daily = $stmt1->fetchAll(PDO::FETCH_ASSOC);


/* =========================================
   SALES VS TARGET
========================================= */

/*
Example target:
Replace 50000000 with your real target table later
*/

$sql2 = "
SELECT
    SUM(CASE WHEN t_type = 'DEL' THEN t_debit ELSE 0 END) AS sales
FROM transactions

WHERE co_id = :comp_id
AND t_status = 'Confirmed'
AND t_copy = 'D'
AND t_type = 'DEL'

AND MONTH(t_date) = MONTH(CURRENT_DATE)
AND YEAR(t_date) = YEAR(CURRENT_DATE)
";

$stmt2 = $pdo->prepare($sql2);

$stmt2->execute([
    'comp_id' => $comp_id
]);

$row = $stmt2->fetch(PDO::FETCH_ASSOC);

$sales = $row['sales'] ?? 0;


/* =========================================
   STATIC TARGET
========================================= */

$target = 50000000;


/* =========================================
   OUTPUT
========================================= */

echo json_encode([
    "daily" => $daily,
    "sales" => $sales,
    "target" => $target
]);