<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';
requirePermission('repair_parts_manage');

$pdo = getDB();
$user = currentUser();

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['part_id'], $_POST['job_id'])) {
    $_SESSION['error'] = 'Invalid request.'; header('Location: repair_jobs.php'); exit;
}

$part_id = (int)$_POST['part_id'];
$job_id = (int)$_POST['job_id'];

try {
    $pdo->beginTransaction();

    // Verify job is not delivered
    $stmt = $pdo->prepare("SELECT repair_status, job_no FROM repair_jobs WHERE id = ?");
    $stmt->execute([$job_id]);
    $job = $stmt->fetch();
    if (!$job) { throw new Exception('Job not found.'); }
    if ($job['repair_status'] === 'Delivered') {
        throw new Exception('Cannot remove parts from a Delivered job.');
    }

    // Get the part record
    $stmt = $pdo->prepare("SELECT rjp.*, p.product_name FROM repair_job_parts rjp JOIN products p ON rjp.product_id = p.id WHERE rjp.id = ? AND rjp.repair_job_id = ?");
    $stmt->execute([$part_id, $job_id]);
    $part = $stmt->fetch();
    if (!$part) { throw new Exception('Part not found.'); }

    $product_id = $part['product_id'];
    $qty = $part['quantity'];
    $total_price = $part['total_price'];

    // Delete the part record
    $pdo->prepare("DELETE FROM repair_job_parts WHERE id = ?")->execute([$part_id]);

    // Restore stock
    $pdo->prepare("UPDATE products SET current_stock = current_stock + ? WHERE id = ?")->execute([$qty, $product_id]);

    // Get new balance
    $stmt = $pdo->prepare("SELECT current_stock FROM products WHERE id = ?");
    $stmt->execute([$product_id]);
    $new_balance = (int)$stmt->fetchColumn();

    $note = 'Removed from repair job ' . $job['job_no'] . ' - ' . $part['product_name'];
    $stmt = $pdo->prepare("INSERT INTO stock_movements (product_id, movement_type, reference_type, reference_id, quantity_in, quantity_out, balance_after, note, created_by) VALUES (?, 'return', 'repair_job', ?, ?, 0, ?, ?, ?)");
    $stmt->execute([$product_id, $job_id, $qty, $new_balance, $note, $user['id']]);

    // Recalculate parts_total and final_amount
    $stmt = $pdo->prepare("SELECT COALESCE(SUM(total_price), 0) FROM repair_job_parts WHERE repair_job_id = ?");
    $stmt->execute([$job_id]);
    $new_parts_total = (float)$stmt->fetchColumn();

    $pdo->prepare("UPDATE repair_jobs SET parts_total = ?, final_amount = ? + labour_charge - discount_amount, updated_at = NOW() WHERE id = ?")->execute([$new_parts_total, $new_parts_total, $job_id]);

    $pdo->commit();
    $_SESSION['success'] = "Part '{$part['product_name']}' removed and stock restored.";

} catch (Exception $e) {
    $pdo->rollBack();
    $_SESSION['error'] = 'Error: ' . $e->getMessage();
}

header("Location: view_repair_job.php?id=$job_id");
exit;
