<?php
/***********************
 * CONFIG
 ***********************/
$DB_HOST = "localhost";
$DB_USER = "primarysales";
$DB_PASS = "S5L7lF01EQZvQrGK";
$DB_NAME = "primarysales_diana";

/* API TOKEN (keep secret) */
$VALID_TOKEN = "6gQ3L9vF99sA33Lm0PpQ2D8c";

/***********************
 * AUTH CHECK
 ***********************/
if (!isset($_GET['token']) || $_GET['token'] !== $VALID_TOKEN) {
    http_response_code(401);
    exit("Unauthorized");
}

/***********************
 * DATE HANDLING
 * Expect: YYYY-MM
 ***********************/
if (!isset($_GET['month'])) {
    http_response_code(400);
    exit("Month parameter required (YYYY-MM)");
}

$month = $_GET['month']; // e.g. 2026-01

$start_date = $month . "-01";
$end_date   = date("Y-m-t", strtotime($start_date));

/***********************
 * DB CONNECTION
 ***********************/
$conn = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if ($conn->connect_error) {
    http_response_code(500);
    exit("DB connection failed");
}

/***********************
 * QUERY
 ***********************/
$sql = "
    SELECT 
        DATE(dates) AS dates,
        agent_names,
        item_names,
        itemcode,
        box_price,
        box_qty,
        (box_qty)*(packets_per_box*packet_weights)/1000000
    FROM rd_targets
    WHERE DATE(dates) BETWEEN ? AND ?
    ORDER BY dates, agent_names
";

$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $start_date, $end_date);
$stmt->execute();
$result = $stmt->get_result();

/***********************
 * CSV OUTPUT HEADERS
 ***********************/
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=rd_targets_$month.csv");
header("Pragma: no-cache");
header("Expires: 0");

/***********************
 * CSV STREAM
 ***********************/
$output = fopen("php://output", "w");

/* CSV HEADER */
fputcsv($output, [
    "Date",
    "Agent Name",
    "Item Name",
    "Item Code",
    "Box Price",
    "Box Qty",
    "Ton"
]);

/* CSV ROWS */
while ($row = $result->fetch_assoc()) {
    fputcsv($output, $row);
}

fclose($output);
$stmt->close();
$conn->close();
exit;
