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

$pdo = getDB();
$user = currentUser();
$user_id = $user['id'];
$is_admin = in_array($user['role_name'], ['Super Admin', 'Admin']);

// Handle status update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    $job_id = (int)$_POST['job_id'];
    $new_status = $_POST['status'];
    $notes = trim($_POST['status_notes']);

    if ($is_admin) {
        $stmt = $pdo->prepare("UPDATE repair_jobs SET repair_status=? WHERE id=?");
        $stmt->execute([$new_status, $job_id]);
    } else {
        $stmt = $pdo->prepare("UPDATE repair_jobs SET repair_status=? WHERE id=? AND assigned_technician_id=?");
        $stmt->execute([$new_status, $job_id, $user_id]);
    }

    $pdo->prepare("INSERT INTO repair_job_status_history (repair_job_id, new_status, note, changed_by) VALUES (?,?,?,?)")
         ->execute([$job_id, $new_status, $notes, $user_id]);

    logActivity('Updated Repair Status', 'Repairs', $job_id, "Status: $new_status");
    $_SESSION['success'] = 'Job status updated.';
    header('Location: technician_panel.php'); exit;
}

// Handle add part from technician
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_part'])) {
    $job_id = (int)$_POST['job_id'];
    $product_id = (int)$_POST['product_id'];
    $qty = (int)$_POST['quantity'];
    $sprice = (float)$_POST['selling_price'];

    $pdo->beginTransaction();
    try {
        $stmt = $pdo->prepare("SELECT current_stock, cost_price FROM products WHERE id=?");
        $stmt->execute([$product_id]);
        $prod = $stmt->fetch();
        if ($prod && $prod['current_stock'] >= $qty) {
            $total = $qty * $sprice;
            $cost_price = $prod['cost_price'];
            $pdo->prepare("INSERT INTO repair_job_parts (repair_job_id, product_id, quantity, cost_price, selling_price, total_price) VALUES (?,?,?,?,?,?)")
                ->execute([$job_id, $product_id, $qty, $cost_price, $sprice, $total]);
            $pdo->prepare("UPDATE products SET current_stock = current_stock - ? WHERE id = ?")->execute([$qty, $product_id]);
            // Stock movement
            $stmt = $pdo->prepare("SELECT current_stock FROM products WHERE id = ?");
            $stmt->execute([$product_id]);
            $new_balance = (int)$stmt->fetchColumn();
            $stmt = $pdo->prepare("SELECT job_no FROM repair_jobs WHERE id = ?");
            $stmt->execute([$job_id]);
            $job_row = $stmt->fetch();
            $pdo->prepare("INSERT INTO stock_movements (product_id, movement_type, reference_type, reference_id, quantity_in, quantity_out, balance_after, note, created_by) VALUES (?, 'repair_usage', 'repair_job', ?, 0, ?, ?, ?, ?)")
                ->execute([$product_id, $job_id, $qty, $new_balance, 'Used in repair job ' . ($job_row['job_no'] ?? ''), $user_id]);
            // Update job totals - recalculate from actual parts
            $stmt = $pdo->prepare("SELECT COALESCE(SUM(total_price), 0) FROM repair_job_parts WHERE repair_job_id = ?");
            $stmt->execute([$job_id]);
            $parts_total = (float)$stmt->fetchColumn();
            $pdo->prepare("UPDATE repair_jobs SET parts_total = ?, final_amount = ? + labour_charge - discount_amount WHERE id = ?")->execute([$parts_total, $parts_total, $job_id]);
            $pdo->commit();
            $_SESSION['success'] = 'Part added to job.';
        } else {
            $_SESSION['error'] = 'Insufficient stock.';
            $pdo->rollBack();
        }
    } catch (Exception $e) { $pdo->rollBack(); $_SESSION['error'] = 'Error: ' . $e->getMessage(); }
    header('Location: technician_panel.php'); exit;
}

// Admin sees all jobs; Technician sees only assigned
if ($is_admin) {
    $stmt = $pdo->prepare("SELECT rj.*, c.name as customer_name, c.phone as customer_phone, u.name as technician_name FROM repair_jobs rj LEFT JOIN customers c ON rj.customer_id = c.id LEFT JOIN users u ON rj.assigned_technician_id = u.id ORDER BY FIELD(rj.repair_status, 'Received','Checking','Waiting for Customer Approval','Waiting for Parts','Repairing','Completed','Delivered'), rj.id DESC");
    $stmt->execute();
} else {
    $stmt = $pdo->prepare("SELECT rj.*, c.name as customer_name, c.phone as customer_phone, u.name as technician_name FROM repair_jobs rj LEFT JOIN customers c ON rj.customer_id = c.id LEFT JOIN users u ON rj.assigned_technician_id = u.id WHERE rj.assigned_technician_id = ? ORDER BY FIELD(rj.repair_status, 'Received','Checking','Waiting for Customer Approval','Waiting for Parts','Repairing','Completed','Delivered'), rj.id DESC");
    $stmt->execute([$user_id]);
}
$my_jobs = $stmt->fetchAll();

$spare_parts = $pdo->query("SELECT id, product_name, current_stock, selling_price FROM products WHERE product_type='spare_part' AND status=1 AND current_stock > 0 ORDER BY product_name")->fetchAll();

include BASE_PATH . 'includes/header.php';
include BASE_PATH . 'includes/sidebar.php';
?>
<div class="content-wrapper">
    <div class="container-fluid">
        <h4 class="page-title"><i class="fas fa-user-cog me-2"></i><?= $is_admin ? 'All Jobs' : 'My Assigned Jobs' ?></h4>

        <?php if (isset($_SESSION['success'])): ?><div class="alert alert-success alert-dismissible"><?= $_SESSION['success']; unset($_SESSION['success']); ?></div><?php endif; ?>
        <?php if (isset($_SESSION['error'])): ?><div class="alert alert-danger alert-dismissible"><?= $_SESSION['error']; unset($_SESSION['error']); ?></div><?php endif; ?>

        <div class="row mb-4">
            <div class="col-md-3">
                <div class="stat-card bg-warning-gradient">
                    <div class="stat-icon"><i class="fas fa-clock"></i></div>
                    <div class="stat-value"><?= count(array_filter($my_jobs, function($j) { return !in_array($j['repair_status'], ['Delivered','Cancelled','Cannot Repair']); })) ?></div>
                    <div class="stat-label">Active Jobs</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card bg-success-gradient">
                    <div class="stat-icon"><i class="fas fa-check-circle"></i></div>
                    <div class="stat-value"><?= count(array_filter($my_jobs, function($j) { return in_array($j['repair_status'], ['Completed','Delivered']); })) ?></div>
                    <div class="stat-label">Completed</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card bg-info-gradient">
                    <div class="stat-icon"><i class="fas fa-dollar-sign"></i></div>
                    <div class="stat-value"><?= formatCurrency(array_sum(array_column(array_filter($my_jobs, function($j) { return $j['repair_status'] == 'Delivered'; }), 'final_amount'))) ?></div>
                    <div class="stat-label">Repair Value</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card bg-primary-gradient">
                    <div class="stat-icon"><i class="fas fa-briefcase"></i></div>
                    <div class="stat-value"><?= count($my_jobs) ?></div>
                    <div class="stat-label"><?= $is_admin ? 'Total Jobs' : 'Total Assigned' ?></div>
                </div>
            </div>
        </div>

        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table id="technicianJobsTable" class="table table-hover datatable">
                        <thead>
                            <tr>
                                <th>Job #</th>
                                <th>Customer</th>
                                <th>Device</th>
                                <th>Problem</th>
                                <?php if ($is_admin): ?><th>Technician</th><?php endif; ?>
                                <th>Parts</th>
                                <th>Total</th>
                                <th>Due</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (count($my_jobs) > 0): ?>
                            <?php foreach ($my_jobs as $j): ?>
                            <tr class="<?= ($j['priority'] ?? '') === 'Urgent' ? 'table-warning' : '' ?>">
                                <td><strong><?= htmlspecialchars($j['job_no']) ?></strong></td>
                                <td><?= htmlspecialchars($j['customer_name'] ?? '-') ?><br><small><?= htmlspecialchars($j['customer_phone'] ?? '') ?></small></td>
                                <td><?= htmlspecialchars($j['device_brand'] ?? '') ?> <?= htmlspecialchars($j['device_model'] ?? '') ?></td>
                                <td><small><?= htmlspecialchars(mb_strlen($j['problem_description'] ?? '') > 50 ? mb_substr($j['problem_description'], 0, 50) . '...' : ($j['problem_description'] ?? '-')) ?></small></td>
                                <?php if ($is_admin): ?><td><?= htmlspecialchars($j['technician_name'] ?? 'Unassigned') ?></td><?php endif; ?>
                                <td><?= formatCurrency($j['parts_total'] ?? 0) ?></td>
                                <td><?= formatCurrency($j['final_amount'] ?? 0) ?></td>
                                <td class="<?= ($j['due_amount'] ?? 0) > 0 ? 'text-danger fw-bold' : '' ?>"><?= formatCurrency($j['due_amount'] ?? 0) ?></td>
                                <td><?= getStatusBadge($j['repair_status']) ?></td>
                                <td>
                                    <div class="btn-group btn-group-sm">
                                        <a href="view_repair_job.php?id=<?= $j['id'] ?>" class="btn btn-sm btn-secondary" title="View"><i class="fas fa-eye"></i></a>
                                        <button class="btn btn-sm btn-primary" onclick="updateStatus(<?= $j['id'] ?>, '<?= $j['repair_status'] ?>')" title="Update Status"><i class="fas fa-check"></i></button>
                                        <?php if (hasPermission('repair_parts_manage') || $is_admin): ?>
                                        <button class="btn btn-sm btn-info" onclick="addPart(<?= $j['id'] ?>)" title="Add Part"><i class="fas fa-plus"></i></button>
                                        <?php endif; ?>
                                        <?php if (!in_array($j['repair_status'], ['Completed', 'Delivered', 'Cancelled', 'Cannot Repair'])): ?>
                                        <a href="edit_repair_job.php?id=<?= $j['id'] ?>" class="btn btn-sm btn-warning" title="Edit"><i class="fas fa-edit"></i></a>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Status Update Modal -->
<div class="modal fade" id="statusModal" tabindex="-1">
    <div class="modal-dialog">
        <form method="POST" class="modal-content">
            <input type="hidden" name="update_status" value="1">
            <input type="hidden" name="job_id" id="statusJobId">
            <div class="modal-header"><h5 class="modal-title">Update Job Status</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">New Status</label>
                    <select name="status" id="statusSelect" class="form-select">
                        <option value="Received">Received</option>
                        <option value="Checking">Checking</option>
                        <option value="Waiting for Customer Approval">Waiting for Customer Approval</option>
                        <option value="Waiting for Parts">Waiting for Parts</option>
                        <option value="Repairing">Repairing</option>
                        <option value="Completed">Completed</option>
                        <option value="Delivered">Delivered</option>
                        <option value="Cancelled">Cancelled</option>
                        <option value="Cannot Repair">Cannot Repair</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">Notes</label>
                    <textarea name="status_notes" class="form-control" rows="3"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" class="btn btn-primary">Update Status</button>
            </div>
        </form>
    </div>
</div>

<!-- Add Part Modal -->
<div class="modal fade" id="partModal" tabindex="-1">
    <div class="modal-dialog">
        <form method="POST" class="modal-content">
            <input type="hidden" name="add_part" value="1">
            <input type="hidden" name="job_id" id="partJobId">
            <div class="modal-header"><h5 class="modal-title">Add Spare Part to Job</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">Spare Part</label>
                    <select name="product_id" class="form-select" required>
                        <option value="">Select</option>
                        <?php foreach ($spare_parts as $sp): ?>
                        <option value="<?= $sp['id'] ?>"><?= htmlspecialchars($sp['product_name']) ?> (Stock: <?= $sp['current_stock'] ?>, Price: <?= $sp['selling_price'] ?>)</option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Quantity</label>
                        <input type="number" name="quantity" class="form-control" value="1" min="1">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Selling Price</label>
                        <input type="number" step="0.01" name="selling_price" class="form-control" value="0">
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" class="btn btn-primary">Add Part</button>
            </div>
        </form>
    </div>
</div>

<script>
function updateStatus(jobId, currentStatus) {
    $('#statusJobId').val(jobId);
    $('#statusSelect').val(currentStatus);
    $('#statusModal').modal('show');
}
function addPart(jobId) {
    $('#partJobId').val(jobId);
    $('#partModal').modal('show');
}
</script>

<?php include BASE_PATH . 'includes/footer.php'; ?>
