<?php
session_start();
require_once 'config/db_config.php'; // Include PDO database connection

// Ensure user is logged in, is an admin
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header("Location: login.php");
    exit();
}

// Initialize variables for form handling
$errors = [];
$success = '';
$cgst_rate = $sgst_rate = '';
$effective_date = '';
$edit_tax_id = null;

// Fetch tax rates
try {
    $stmt = $pdo->prepare("
        SELECT tax_id, cgst_rate, sgst_rate, effective_date
        FROM taxes
        ORDER BY effective_date DESC
    ");
    $stmt->execute();
    $taxes = $stmt->fetchAll();
} catch (PDOException $e) {
    $errors[] = "Error fetching tax rates: " . $e->getMessage();
}

// Handle form submission (add or edit)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    
    $cgst_rate = trim($_POST['cgst_rate'] ?? '');
    $sgst_rate = trim($_POST['sgst_rate'] ?? '');
    $effective_date = $_POST['effective_date'] ?? '';

    // Validate inputs
    if (!is_numeric($cgst_rate) || $cgst_rate < 0) {
        $errors[] = "CGST rate must be a non-negative number.";
    }
    if (!is_numeric($sgst_rate) || $sgst_rate < 0) {
        $errors[] = "SGST rate must be a non-negative number.";
    }
    if (empty($effective_date)) {
        $errors[] = "Effective date is required.";
    } else {
        $effective_date_obj = DateTime::createFromFormat('Y-m-d', $effective_date);
        if (!$effective_date_obj || $effective_date_obj->format('Y-m-d') !== $effective_date) {
            $errors[] = "Invalid effective date format.";
        } elseif ($action === 'add' && $effective_date < date('Y-m-d')) {
            $errors[] = "Effective date cannot be in the past for new tax rates.";
        }
    }

    // Check for overlapping effective dates
    if (empty($errors)) {
        try {
            $stmt = $pdo->prepare("
                SELECT COUNT(*) FROM taxes 
                WHERE effective_date = :effective_date 
                AND tax_id != :tax_id
            ");
            $stmt->execute([
                'effective_date' => $effective_date,
                'tax_id' => $action === 'edit' ? ($_POST['tax_id'] ?? 0) : 0
            ]);
            if ($stmt->fetchColumn() > 0) {
                $errors[] = "A tax rate already exists for this effective date.";
            }
        } catch (PDOException $e) {
            $errors[] = "Error checking effective date: " . $e->getMessage();
        }
    }

    // Perform add or edit
    if (empty($errors)) {
        try {
            if ($action === 'add') {
                $stmt = $pdo->prepare("
                    INSERT INTO taxes (cgst_rate, sgst_rate, effective_date, created_at)
                    VALUES (:cgst_rate, :sgst_rate, :effective_date, NOW())
                ");
                $stmt->execute([
                    'cgst_rate' => $cgst_rate,
                    'sgst_rate' => $sgst_rate,
                    'effective_date' => $effective_date
                ]);
                $success = "Tax rate added successfully!";
            } elseif ($action === 'edit') {
                $tax_id = $_POST['tax_id'];
                $stmt = $pdo->prepare("
                    UPDATE taxes 
                    SET cgst_rate = :cgst_rate, sgst_rate = :sgst_rate, effective_date = :effective_date
                    WHERE tax_id = :tax_id
                ");
                $stmt->execute([
                    'cgst_rate' => $cgst_rate,
                    'sgst_rate' => $sgst_rate,
                    'effective_date' => $effective_date,
                    'tax_id' => $tax_id
                ]);
                $success = "Tax rate updated successfully!";
            }
            $cgst_rate = $sgst_rate = $effective_date = '';
            $edit_tax_id = null;
        } catch (PDOException $e) {
            $errors[] = "Error saving tax rate: " . $e->getMessage();
        }
    }
}

// Handle delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_tax_id'])) {
    $tax_id = $_POST['delete_tax_id'];
    try {
        // Check if tax rate is in use (simplified; assumes future effective dates are safe to delete)
        $stmt = $pdo->prepare("SELECT effective_date FROM taxes WHERE tax_id = :tax_id");
        $stmt->execute(['tax_id' => $tax_id]);
        $tax = $stmt->fetch();
        if ($tax && $tax['effective_date'] <= date('Y-m-d')) {
            $errors[] = "Cannot delete tax rate: It is currently in effect or was in the past.";
        } else {
            $stmt = $pdo->prepare("DELETE FROM taxes WHERE tax_id = :tax_id");
            $stmt->execute(['tax_id' => $tax_id]);
            $success = "Tax rate deleted successfully!";
        }
    } catch (PDOException $e) {
        $errors[] = "Error deleting tax rate: " . $e->getMessage();
    }
}

// Fetch tax rate for editing
if (isset($_GET['edit'])) {
    $edit_tax_id = $_GET['edit'];
    try {
        $stmt = $pdo->prepare("
            SELECT cgst_rate, sgst_rate, effective_date
            FROM taxes 
            WHERE tax_id = :tax_id
        ");
        $stmt->execute(['tax_id' => $edit_tax_id]);
        $tax = $stmt->fetch();
        if ($tax) {
            $cgst_rate = $tax['cgst_rate'];
            $sgst_rate = $tax['sgst_rate'];
            $effective_date = $tax['effective_date'];
        } else {
            $errors[] = "Tax rate not found.";
            $edit_tax_id = null;
        }
    } catch (PDOException $e) {
        $errors[] = "Error fetching tax rate: " . $e->getMessage();
    }
}
?>

<?php include './partials/layouts/layoutTop.php' ?>

<style>
/* Mobile responsive adjustments */
@media (max-width: 768px) {
    .dashboard-main-body {
        padding-bottom: 80px;
    }
    .small-table { font-size: 0.8rem; }
    .small-table th, .small-table td { padding: 6px 8px; }
}
/* Card styling for mobile view */
.tax-card {
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.tax-card .card-body {
    padding: 16px;
}
.tax-card .card-title {
    font-size: 1rem;
    font-weight: 600;
    margin-bottom: 8px;
}
.tax-card .text-sm {
    font-size: 0.85rem;
}
.tax-card .text-muted {
    color: #6c757d !important;
}
/* Icon styling */
.fa-icon {
    font-size: 14px;
    margin-right: 4px;
}
.small-table { font-size: 0.85rem; }
.small-table th, .small-table td { padding: 8px 12px; }
</style>

<div class="dashboard-main-body">
    <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-24">
        <h6 class="fw-semibold mb-0">Tax Rates</h6>
        <ul class="d-flex align-items-center gap-2">
            <li class="fw-medium">
                <a href="index.php" class="d-flex align-items-center gap-1 hover-text-primary">
                    <i class="fas fa-home fa-icon"></i>
                    Dashboard
                </a>
            </li>
            <li>-</li>
            <li class="fw-medium">Tax Rates</li>
        </ul>
    </div>

    <div class="card">
        <div class="card-body p-24">
            <h6 class="section-title text-lg mb-16"><?php echo $edit_tax_id ? 'Edit Tax Rate' : 'Add New Tax Rate'; ?></h6>

            <!-- Display success or error messages -->
            <?php if ($success): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <?php echo htmlspecialchars($success); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            <?php endif; ?>
            <?php if (!empty($errors)): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <ul class="mb-0">
                        <?php foreach ($errors as $error): ?>
                            <li><?php echo htmlspecialchars($error); ?></li>
                        <?php endforeach; ?>
                    </ul>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            <?php endif; ?>

            <!-- Tax Rate Form (Add/Edit) -->
            <form action="taxes.php" method="POST">
                <input type="hidden" name="action" value="<?php echo $edit_tax_id ? 'edit' : 'add'; ?>">
                <?php if ($edit_tax_id): ?>
                    <input type="hidden" name="tax_id" value="<?php echo $edit_tax_id; ?>">
                <?php endif; ?>
                <div class="row gy-4">
                    <div class="col-md-3">
                        <label for="cgst_rate" class="form-label fw-medium">CGST Rate (%) <span class="text-danger">*</span></label>
                        <input type="number" step="0.01" min="0" class="form-control bg-base" id="cgst_rate" name="cgst_rate" value="<?php echo htmlspecialchars($cgst_rate); ?>" required>
                    </div>
                    <div class="col-md-3">
                        <label for="sgst_rate" class="form-label fw-medium">SGST Rate (%) <span class="text-danger">*</span></label>
                        <input type="number" step="0.01" min="0" class="form-control bg-base" id="sgst_rate" name="sgst_rate" value="<?php echo htmlspecialchars($sgst_rate); ?>" required>
                    </div>
                    <div class="col-md-3">
                        <label for="effective_date" class="form-label fw-medium">Effective Date <span class="text-danger">*</span></label>
                        <input type="date" class="form-control bg-base" id="effective_date" name="effective_date" value="<?php echo htmlspecialchars($effective_date); ?>" required>
                    </div>
                    <div class="col-12 text-end">
                        <button type="submit" class="btn btn-primary bg-primary-600 hover-bg-primary-700 text-white">
                            <i class="fas fa-save fa-icon"></i>
                            <?php echo $edit_tax_id ? 'Update Tax Rate' : 'Add Tax Rate'; ?>
                        </button>
                        <?php if ($edit_tax_id): ?>
                            <a href="taxes.php" class="btn btn-outline-secondary">
                                <i class="fas fa-times fa-icon"></i> Cancel
                            </a>
                        <?php endif; ?>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Tax Rates List -->
    <div class="card mt-24">
        <div class="card-body p-24">
            <h6 class="section-title text-lg mb-16">All Tax Rates (<?php echo count($taxes); ?>)</h6>

            <!-- Desktop Table View -->
            <div class="d-none d-lg-block">
                <div class="table-responsive scroll-sm">
                    <table class="table bordered-table sm-table small-table mb-0">
                        <thead>
                            <tr>
                                <th scope="col">CGST Rate (%)</th>
                                <th scope="col">SGST Rate (%)</th>
                                <th scope="col">Effective Date</th>
                                <th scope="col" class="text-center">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($taxes)): ?>
                               
                            <?php else: ?>
                                <?php foreach ($taxes as $tax): ?>
                                    <tr>
                                        <td><?php echo number_format($tax['cgst_rate'], 2); ?></td>
                                        <td><?php echo number_format($tax['sgst_rate'], 2); ?></td>
                                        <td><?php echo date('d M Y', strtotime($tax['effective_date'])); ?></td>
                                        <td class="text-center">
                                            <div class="d-flex gap-1 justify-content-center">
                                                <a href="taxes.php?edit=<?php echo $tax['tax_id']; ?>"
                                                   class="w-32-px h-32-px bg-success-focus text-success-main rounded-circle d-inline-flex align-items-center justify-content-center">
                                                    <i class="fas fa-edit fa-icon"></i>
                                                </a>
                                                <form action="taxes.php" method="POST" style="display:inline;" onsubmit="return confirm('Are you sure you want to delete this tax rate?');">
                                                    <input type="hidden" name="delete_tax_id" value="<?php echo $tax['tax_id']; ?>">
                                                    <button type="submit" class="w-32-px h-32-px bg-danger-focus text-danger-main rounded-circle d-inline-flex align-items-center justify-content-center border-0 bg-none">
                                                        <i class="fas fa-trash fa-icon"></i>
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Mobile Card View -->
            <div class="d-block d-lg-none">
                <?php if (empty($taxes)): ?>
                    <div class="text-center text-sm py-4">
                        <div class="d-flex flex-column align-items-center">
                            <i class="fas fa-percent text-3xl text-secondary mb-2"></i>
                            <span>No tax rates found</span>
                        </div>
                    </div>
                <?php else: ?>
                    <div class="row g-3">
                        <?php foreach ($taxes as $index => $tax): ?>
                            <div class="col-12">
                                <div class="card tax-card shadow-sm">
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between align-items-start mb-2">
                                            <h6 class="card-title mb-0 text-sm fw-bold">
                                                <i class="fas fa-percent fa-icon"></i>
                                                Tax Rate #<?php echo sprintf('%02d', $index + 1); ?>
                                            </h6>
                                            <div class="form-check style-check">
                                                <label class="form-check-label text-sm">S.L: <?php echo sprintf('%02d', $index + 1); ?></label>
                                            </div>
                                        </div>
                                        <div class="mb-2">
                                            <p class="text-sm mb-1">
                                                <strong><i class="fas fa-percentage fa-icon"></i> CGST Rate:</strong> <?php echo number_format($tax['cgst_rate'], 2); ?>%
                                            </p>
                                            <p class="text-sm mb-1">
                                                <strong><i class="fas fa-percentage fa-icon"></i> SGST Rate:</strong> <?php echo number_format($tax['sgst_rate'], 2); ?>%
                                            </p>
                                            <p class="text-sm mb-1">
                                                <strong><i class="fas fa-calendar-alt fa-icon"></i> Effective Date:</strong> <?php echo date('d M Y', strtotime($tax['effective_date'])); ?>
                                            </p>
                                        </div>
                                        <div class="d-flex justify-content-end align-items-center mt-3">
                                            <div class="d-flex gap-2">
                                                <a href="taxes.php?edit=<?php echo $tax['tax_id']; ?>"
                                                   class="btn btn-sm btn-outline-success">
                                                    <i class="fas fa-edit fa-icon"></i> Edit
                                                </a>
                                                <form action="taxes.php" method="POST" style="display:inline;" onsubmit="return confirm('Are you sure you want to delete this tax rate?');">
                                                    <input type="hidden" name="delete_tax_id" value="<?php echo $tax['tax_id']; ?>">
                                                    <button type="submit" class="btn btn-sm btn-outline-danger">
                                                        <i class="fas fa-trash fa-icon"></i> Delete
                                                    </button>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php include './partials/layouts/layoutBottom.php' ?>