<?php
/**
 * Manpower Transfer Approval
 * Only HR Admin and Super Admin can approve transfers.
 */

require_once __DIR__ . '/../../includes/init.php';
requireLogin();

// Access control: only HR Admin or Super Admin
if (!isHRAdmin() && !isSuperAdmin()) {
    redirect(BASE_URL . '/modules/transfer/list.php', 'You do not have permission to approve transfers.', 'error');
}

$pageTitle = 'Manpower Transfer Approval';
$currentModule = 'transfer';

// Filters
$today = new DateTimeImmutable();
$month = isset($_GET['month']) ? (int)$_GET['month'] : (int)$today->format('m');
$year = isset($_GET['year']) ? (int)$_GET['year'] : (int)$today->format('Y');
$statusFilter = sanitize($_GET['status'] ?? 'pending'); // pending, approved, all
$search = trim(sanitize($_GET['search'] ?? ''));

// Normalize month/year and derive date range from them
$month = max(1, min(12, $month));
$year = $year > 1970 ? $year : (int)$today->format('Y');
$fromDate = (new DateTimeImmutable(sprintf('%04d-%02d-01', $year, $month)))->format('Y-m-d');
$toDate = (new DateTimeImmutable($fromDate))->modify('last day of this month')->format('Y-m-d');

$db = getDB();
$userId = getCurrentUserId();

// Handle approvals (single / bulk)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    // Preserve filter values from hidden fields
    $statusFilter = sanitize($_POST['status'] ?? $statusFilter);
    $search = trim(sanitize($_POST['search'] ?? $search));

    try {
        if ($action === 'approve_selected') {
            $selected = $_POST['transfer_ids'] ?? [];
            if (!empty($selected) && is_array($selected)) {
                $ids = array_map('intval', $selected);
                $positiveIds = array_filter($ids, fn($id) => $id > 0);

                if (!empty($positiveIds)) {
                    // Normal case: approve by specific transfer_id list
                    $placeholders = implode(',', array_fill(0, count($positiveIds), '?'));
                    $sql = "
                        UPDATE employee_transfers
                        SET transfer_status = 'approved',
                            approved_by = ?,
                            approved_at = NOW()
                        WHERE transfer_id IN ($placeholders)
                          AND transfer_status = 'pending'
                    ";
                    $stmt = $db->prepare($sql);
                    $params = array_merge([$userId], $positiveIds);
                    $stmt->execute($params);
                    $approvedCount = $stmt->rowCount();
                    setFlashMessage('success', "Approved {$approvedCount} transfer(s) successfully.");
                } else {
                    // Fallback: when transfer_id values are 0 (old data),
                    // approve all pending transfers in the current period
                    $sql = "
                        UPDATE employee_transfers
                        SET transfer_status = 'approved',
                            approved_by = ?,
                            approved_at = NOW()
                        WHERE transfer_status = 'pending'
                          AND transfer_date BETWEEN ? AND ?
                    ";
                    $stmt = $db->prepare($sql);
                    $stmt->execute([$userId, $fromDate, $toDate]);
                    $approvedCount = $stmt->rowCount();
                    setFlashMessage('success', "Approved {$approvedCount} transfer(s) successfully.");
                }
            }
        } elseif ($action === 'approve_all') {
            $sql = "
                UPDATE employee_transfers
                SET transfer_status = 'approved',
                    approved_by = ?,
                    approved_at = NOW()
                WHERE transfer_status = 'pending'
                  AND transfer_date BETWEEN ? AND ?
            ";
            $stmt = $db->prepare($sql);
            $stmt->execute([$userId, $fromDate, $toDate]);
            $approvedCount = $stmt->rowCount();
            setFlashMessage('success', "Approved {$approvedCount} transfer(s) in the selected period.");
        }
    } catch (Exception $e) {
        error_log('Transfer approval error: ' . $e->getMessage());
        setFlashMessage('error', 'Error approving transfers. Please try again.');
    }

    // Redirect to avoid form resubmission
    $query = http_build_query([
        'from_date' => $fromDate,
        'to_date' => $toDate,
        'month' => $month,
        'year' => $year,
        'status' => $statusFilter,
        'search' => $search,
    ]);
    header('Location: ' . BASE_URL . '/modules/transfer/approve.php?' . $query);
    exit;
}

// Load transfers for display (based on status filter)
$transfers = [];
try {
    $sql = "
        SELECT
            t.transfer_id,
            t.employee_id,
            t.employee_category,
            t.from_site_id,
            t.from_location,
            t.to_site_id,
            t.to_location,
            t.transfer_date,
            t.effective_branch,
            t.effective_attendance,
            t.esi_applicability,
            t.transfer_form_filled,
            t.approved_by_district_head,
            t.transfer_reason,
            t.transfer_status,
            t.created_at,
            t.approved_at,
            e.employee_code,
            CONCAT(e.first_name, ' ', COALESCE(e.middle_name, ''), ' ', e.last_name) AS full_name,
            d.designation_name,
            fs.site_name AS from_site_name,
            ts.site_name AS to_site_name
        FROM employee_transfers t
        INNER JOIN employees e ON t.employee_id = e.employee_id
        LEFT JOIN designations d ON e.designation_id = d.designation_id
        LEFT JOIN sites fs ON t.from_site_id = fs.site_id
        LEFT JOIN sites ts ON t.to_site_id = ts.site_id
        WHERE 1=1
    ";

    $params = [];

    // Date + status filter logic:
    if ($statusFilter === 'approved') {
        // For approved status, filter by approval date
        $sql .= " AND t.transfer_status = 'approved' AND DATE(t.approved_at) BETWEEN :from_date AND :to_date";
        $params[':from_date'] = $fromDate;
        $params[':to_date'] = $toDate;
    } elseif ($statusFilter === 'pending') {
        // For pending status, filter by transfer date
        $sql .= " AND t.transfer_status = 'pending' AND t.transfer_date BETWEEN :from_date AND :to_date";
        $params[':from_date'] = $fromDate;
        $params[':to_date'] = $toDate;
    } else {
        // For 'all' status, include:
        // - pending transfers by transfer_date
        // - approved transfers by approved_at
        $sql .= " AND (
            (t.transfer_status = 'pending' AND t.transfer_date BETWEEN :from_date AND :to_date)
            OR
            (t.transfer_status = 'approved' AND DATE(t.approved_at) BETWEEN :from_date AND :to_date)
        )";
        $params[':from_date'] = $fromDate;
        $params[':to_date'] = $toDate;
    }

    // Search filter (emp code or name)
    if ($search !== '') {
        $sql .= " AND (e.employee_code LIKE :search OR CONCAT(e.first_name, ' ', COALESCE(e.middle_name, ''), ' ', e.last_name) LIKE :search)";
        $params[':search'] = '%' . $search . '%';
    }

    // Ordering: for approved, order by approved_at; otherwise by transfer_date
    if ($statusFilter === 'approved') {
        $sql .= " ORDER BY t.approved_at DESC, t.transfer_id DESC";
    } else {
        $sql .= " ORDER BY t.transfer_date ASC, t.transfer_id ASC";
    }

    $sql .= " LIMIT 1000";

    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $transfers = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    error_log('Transfer approval load error: ' . $e->getMessage());
    setFlashMessage('error', 'Error loading pending transfers.');
}

include __DIR__ . '/../../includes/header.php';
?>

<style>
.transfer-approve-table-wrapper {
    overflow-x: auto;
}
.transfer-approve-table th,
.transfer-approve-table td {
    white-space: nowrap;
}
</style>

<div class="table-container">
    <div class="table-header">
        <div>
            <h2 class="table-title">Manpower Transfer Approval</h2>
            <p style="margin-top: 4px; color: var(--text-secondary); font-size: 13px;">
                Approve pending transfers one by one or in bulk (HR/Admin only). Use filters to view pending or approved transfers.
            </p>
        </div>
        <div class="table-actions">
            <a href="<?php echo BASE_URL; ?>/modules/transfer/list.php" class="btn btn-secondary btn-sm">Back to Transfer Entry</a>
            <a href="<?php echo BASE_URL; ?>/modules/transfer/report.php" class="btn btn-secondary btn-sm">View Report</a>
        </div>
    </div>

    <form method="GET" class="table-filters">
        <div class="filter-group">
            <label for="from_date">From Date</label>
            <input type="date" id="from_date" name="from_date" class="form-control"
                   value="<?php echo htmlspecialchars($fromDate); ?>">
        </div>
        <div class="filter-group">
            <label for="to_date">To Date</label>
            <input type="date" id="to_date" name="to_date" class="form-control"
                   value="<?php echo htmlspecialchars($toDate); ?>">
        </div>
        <div class="filter-group">
            <label for="month">Month</label>
            <select id="month" name="month" class="form-control">
                <?php for ($m = 1; $m <= 12; $m++): ?>
                    <option value="<?php echo $m; ?>" <?php echo $m === $month ? 'selected' : ''; ?>>
                        <?php echo date('F', mktime(0, 0, 0, $m, 1)); ?>
                    </option>
                <?php endfor; ?>
            </select>
        </div>
        <div class="filter-group">
            <label for="year">Year</label>
            <input type="number" id="year" name="year" class="form-control"
                   value="<?php echo htmlspecialchars($year); ?>" min="2000" max="2100" step="1">
        </div>
        <div class="filter-group">
            <label for="status">Status</label>
            <select id="status" name="status" class="form-control">
                <option value="pending" <?php echo $statusFilter === 'pending' ? 'selected' : ''; ?>>Pending</option>
                <option value="approved" <?php echo $statusFilter === 'approved' ? 'selected' : ''; ?>>Approved</option>
                <option value="all" <?php echo $statusFilter === 'all' ? 'selected' : ''; ?>>All</option>
            </select>
        </div>
        <div class="filter-group">
            <label for="search">Search (Emp Code / Employee Name)</label>
            <input type="text" id="search" name="search" class="form-control"
                   placeholder="e.g. 001 or Employee Name" value="<?php echo htmlspecialchars($search); ?>">
        </div>
        <div class="filter-group" style="max-width: 220px;">
            <label>&nbsp;</label>
            <div style="display: flex; gap: 8px;">
                <button type="submit" class="btn btn-primary">Filter</button>
                <button type="submit" name="use_month_year" value="1" class="btn btn-secondary">
                    Use Month/Year
                </button>
            </div>
        </div>
    </form>

    <form method="POST">
        <input type="hidden" name="from_date" value="<?php echo htmlspecialchars($fromDate); ?>">
        <input type="hidden" name="to_date" value="<?php echo htmlspecialchars($toDate); ?>">
        <input type="hidden" name="status" value="<?php echo htmlspecialchars($statusFilter); ?>">
        <input type="hidden" name="search" value="<?php echo htmlspecialchars($search); ?>">

        <div class="transfer-table-wrapper transfer-approve-table-wrapper" style="border-top: 1px solid var(--border-color);">
            <table class="data-table transfer-approve-table">
                <thead>
                    <tr>
                        <th style="width: 40px; text-align:center;">
                            <input type="checkbox" id="select_all" onclick="toggleAllTransfers(this)">
                        </th>
                        <th>Sl No</th>
                        <th>Transfer ID</th>
                        <th>Emp Code</th>
                        <th>Employee Name</th>
                        <th>Designation</th>
                        <th>Category</th>
                        <th>From Site</th>
                        <th>From Location</th>
                        <th>To Site</th>
                        <th>To Location</th>
                        <th>W.E.F</th>
                        <th>Effective Branch</th>
                        <th>Effective Attendance</th>
                        <th>ESI</th>
                        <th>Remarks</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($transfers)): ?>
                        <tr>
                            <td colspan="12" class="text-center" style="padding: 30px; color: var(--text-secondary);">
                                No transfers found for the selected period.
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php $i = 1; foreach ($transfers as $row): ?>
                            <tr>
                                <td style="text-align:center;">
                                    <input type="checkbox" name="transfer_ids[]" value="<?php echo (int)$row['transfer_id']; ?>">
                                </td>
                                <td><?php echo $i++; ?></td>
                                <td><?php echo (int)$row['transfer_id']; ?></td>
                                <td><?php echo htmlspecialchars($row['employee_code']); ?></td>
                                <td><?php echo htmlspecialchars($row['full_name']); ?></td>
                                <td><?php echo htmlspecialchars($row['designation_name'] ?? ''); ?></td>
                                <td><?php echo htmlspecialchars($row['employee_category'] ?? ''); ?></td>
                                <td><?php echo htmlspecialchars($row['from_site_name'] ?? ''); ?></td>
                                <td><?php echo htmlspecialchars($row['from_location'] ?? ''); ?></td>
                                <td><?php echo htmlspecialchars($row['to_site_name'] ?? ''); ?></td>
                                <td><?php echo htmlspecialchars($row['to_location'] ?? ''); ?></td>
                                <td><?php echo htmlspecialchars($row['transfer_date']); ?></td>
                                <td><?php echo htmlspecialchars($row['effective_branch'] ?? ''); ?></td>
                                <td><?php echo htmlspecialchars($row['effective_attendance'] ?? ''); ?></td>
                                <td><?php echo htmlspecialchars($row['esi_applicability'] ?? ''); ?></td>
                                <td><?php echo htmlspecialchars($row['transfer_reason'] ?? ''); ?></td>
                                <td><?php echo htmlspecialchars($row['transfer_status'] ?? 'pending'); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <?php if (!empty($transfers) && $statusFilter === 'pending'): ?>
            <div class="table-footer">
                <div class="table-info">
                    <?php echo count($transfers); ?> pending transfer(s) in this period.
                </div>
                <div>
                    <button type="submit" name="action" value="approve_selected" class="btn btn-primary">
                        Approve Selected
                    </button>
                    <button type="submit" name="action" value="approve_all" class="btn btn-success"
                            onclick="return confirm('Approve ALL pending transfers in this date range?');">
                        Approve All (This Period)
                    </button>
                </div>
            </div>
        <?php endif; ?>
    </form>
</div>

<script>
function toggleAllTransfers(source) {
    const checkboxes = document.querySelectorAll('input[name="transfer_ids[]"]');
    checkboxes.forEach(cb => { cb.checked = source.checked; });
}
</script>

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


