<?php
// api/discounts.php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

require_once __DIR__ . '/../../config.php';

$action = isset($_GET['action']) ? $_GET['action'] : 'list';

function parseDateOrNull($s) {
    if (!$s) return null;
    $t = strtotime($s);
    return $t ? date('Y-m-d', $t) : null;
}

try {
    if ($action === 'list') {
        $sql = "
            SELECT
                Id,
                Name,
                Code,
                Type,
                PercentageValue,
                AmountValue,
                StartDate,
                EndDate,
                MaxUses,
                TimesUsed,
                IsActive,
                CreatedAt
            FROM Discounts
            ORDER BY CreatedAt DESC, Id DESC
        ";
        $stmt = $pdo->query($sql);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $out = [];
        foreach ($rows as $r) {
            $type = $r['Type'];
            $value = $type === 'PERCENTAGE'
                ? (float)($r['PercentageValue'] ?? 0)
                : (float)($r['AmountValue'] ?? 0);

            $startDate = $r['StartDate'] ? date('Y-m-d', strtotime($r['StartDate'])) : null;
            $endDate   = $r['EndDate']   ? date('Y-m-d', strtotime($r['EndDate']))   : null;

            $out[] = [
                'Id'                 => (int)$r['Id'],
                'Name'               => $r['Name'],
                'Code'               => $r['Code'],
                'Type'               => $type,
                'Value'              => $value,
                'StartDate'          => $startDate,
                'EndDate'            => $endDate,
                'StartDateFormatted' => $startDate ? date('d M Y', strtotime($startDate)) : null,
                'EndDateFormatted'   => $endDate   ? date('d M Y', strtotime($endDate))   : null,
                'MaxUses'            => is_null($r['MaxUses']) ? null : (int)$r['MaxUses'],
                'TimesUsed'          => is_null($r['TimesUsed']) ? 0 : (int)$r['TimesUsed'],
                'IsActive'           => is_null($r['IsActive']) ? 0 : (int)$r['IsActive'],
            ];
        }

        echo json_encode(['discounts' => $out]);
        exit;
    }

    if ($action === 'save') {
        $body = json_decode(file_get_contents('php://input'), true);
        if (!is_array($body)) {
            http_response_code(400);
            echo json_encode(['error' => 'Invalid JSON body']);
            exit;
        }

        $id        = isset($body['id']) ? (int)$body['id'] : null;
        $name      = trim($body['name'] ?? '');
        $code      = trim($body['code'] ?? '');
        $type      = $body['type'] === 'AMOUNT' ? 'AMOUNT' : 'PERCENTAGE';
        $value     = (float)($body['value'] ?? 0);
        $startDate = parseDateOrNull($body['startDate'] ?? null);
        $endDate   = parseDateOrNull($body['endDate'] ?? null);
        $maxUses   = isset($body['maxUses']) && $body['maxUses'] !== null ? (int)$body['maxUses'] : null;
        $isActive  = !empty($body['isActive']) ? 1 : 0;

        if ($name === '' || $code === '' || !$value) {
            http_response_code(400);
            echo json_encode(['error' => 'Name, Code and Value are required.']);
            exit;
        }

        // map to columns
        $percentageValue = $type === 'PERCENTAGE' ? $value : null;
        $amountValue     = $type === 'AMOUNT' ? $value : null;

        if ($id) {
            // update
            $sql = "
                UPDATE Discounts
                SET
                    Name = :name,
                    Code = :code,
                    Type = :type,
                    PercentageValue = :pval,
                    AmountValue = :aval,
                    StartDate = :startDate,
                    EndDate = :endDate,
                    MaxUses = :maxUses,
                    IsActive = :isActive
                WHERE Id = :id
            ";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                ':name'      => $name,
                ':code'      => $code,
                ':type'      => $type,
                ':pval'      => $percentageValue,
                ':aval'      => $amountValue,
                ':startDate' => $startDate,
                ':endDate'   => $endDate,
                ':maxUses'   => $maxUses,
                ':isActive'  => $isActive,
                ':id'        => $id
            ]);
        } else {
            // insert
            $sql = "
                INSERT INTO Discounts
                    (Name, Code, Type, PercentageValue, AmountValue, StartDate, EndDate, MaxUses, TimesUsed, IsActive, CreatedAt)
                VALUES
                    (:name, :code, :type, :pval, :aval, :startDate, :endDate, :maxUses, 0, :isActive, NOW())
            ";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                ':name'      => $name,
                ':code'      => $code,
                ':type'      => $type,
                ':pval'      => $percentageValue,
                ':aval'      => $amountValue,
                ':startDate' => $startDate,
                ':endDate'   => $endDate,
                ':maxUses'   => $maxUses,
                ':isActive'  => $isActive
            ]);

            $id = (int)$pdo->lastInsertId();
        }

        echo json_encode(['success' => true, 'id' => $id]);
        exit;
    }

    http_response_code(400);
    echo json_encode(['error' => 'Unknown action']);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'error'   => 'Discounts API failure',
        'details' => $e->getMessage()
    ]);
}
