<?php
session_start();
if (!isset($_SESSION['username'])) {
    http_response_code(403);
    exit("Unauthorized");
}

require_once '../includes/db.php';

$action = $_POST['action'] ?? '';

/* =====================
   DISCOUNT FIRST
   ===================== */
if ($action === 'ajax_add_discount') {

    $bill_id = (int)$_POST['bill_id'];
    $percent = (float)$_POST['discount_percent'];

    if ($bill_id <= 0 || $percent <= 0 || $percent > 100) {
        http_response_code(400);
        echo "Invalid discount input.";
        exit;
    }

    // Get subtotal (exclude previous discounts)
    $stmt = $pdo->prepare("
        SELECT COALESCE(SUM(total),0)
        FROM jobs
        WHERE bill_id = ?
        AND total > 0
    ");
    $stmt->execute([$bill_id]);
    $subtotal = (float)$stmt->fetchColumn();

    if ($subtotal <= 0) {
        http_response_code(400);
        echo "No items to discount.";
        exit;
    }

    $discount_amount = round(($subtotal * $percent) / 100, 2) * -1;

    $job_type_id = $pdo
        ->query("SELECT job_type_id FROM job_types WHERE job_name='Discount - Percentage'")
        ->fetchColumn();

    $stmt = $pdo->prepare("
        INSERT INTO jobs (bill_id, job_type_id, rate, qty, total)
        VALUES (?, ?, ?, ?, ?)
    ");
    $stmt->execute([
        $bill_id,
        $job_type_id,
        $percent,
        1,
        $discount_amount
    ]);

    echo "success";
    exit;
}

/* =====================
   NORMAL JOB ADD
   ===================== */

$bill_id = intval($_POST['bill_id'] ?? 0);
$job_type_id = intval($_POST['job_type_id'] ?? 0);
$rate = floatval($_POST['rate'] ?? 0);
$qty = floatval($_POST['qty'] ?? 0);

if ($bill_id <= 0 || $job_type_id <= 0 || $rate <= 0 || $qty <= 0) {
    http_response_code(400);
    echo "Invalid input.";
    exit;
}

$total = round($rate * $qty, 2);

try {
    $stmt = $pdo->prepare("
        INSERT INTO jobs (bill_id, job_type_id, rate, qty, total)
        VALUES (?, ?, ?, ?, ?)
    ");
    $stmt->execute([$bill_id, $job_type_id, $rate, $qty, $total]);
    echo "success";
} catch (PDOException $e) {
    http_response_code(500);
    echo "Database error: " . $e->getMessage();
}


    // Get subtotal (jobs only, excluding previous discounts)
    $stmt = $pdo->prepare("
        SELECT COALESCE(SUM(total),0)
        FROM jobs
        WHERE bill_id = ?
        AND total > 0
    ");
    $stmt->execute([$bill_id]);
    $subtotal = (float)$stmt->fetchColumn();

    if ($subtotal <= 0) {
        die('No items to discount');
    }

    $discount_amount = round(($subtotal * $percent) / 100, 2) * -1;

    // Get discount job_type_id
    $jt = $pdo->query("SELECT job_type_id FROM job_types WHERE job_name='Discount - Percentage'")->fetchColumn();

    $stmt = $pdo->prepare("
        INSERT INTO jobs (bill_id, job_type_id, rate, qty, total)
        VALUES (?, ?, ?, ?, ?)
    ");
    $stmt->execute([
        $bill_id,
        $jt,
        $percent,
        1,
        $discount_amount
    ]);

    echo 'success';
    exit;
}

try {
    $stmt = $pdo->prepare("INSERT INTO jobs (bill_id, job_type_id, rate, qty, total) VALUES (?, ?, ?, ?, ?)");
    $stmt->execute([$bill_id, $job_type_id, $rate, $qty, $total]);
    echo "success";
} catch (PDOException $e) {
    http_response_code(500);
    echo "Database error: " . $e->getMessage();
}
