<?php
session_start();
require_once 'config/db_config.php';

// 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(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $errors[] = "Error fetching tax rates: " . $e->getMessage();
    error_log("Tax fetch error: " . $e->getMessage());
}

// Handle form submission (add or edit)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // Check which action is being performed
    if (isset($_POST['delete_tax_id'])) {
        // Handle delete
        $tax_id = (int)$_POST['delete_tax_id'];
        try {
            // Check if tax rate is in use
            $stmt = $pdo->prepare("SELECT effective_date FROM taxes WHERE tax_id = :tax_id");
            $stmt->execute(['tax_id' => $tax_id]);
            $tax = $stmt->fetch(PDO::FETCH_ASSOC);
            
            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]);
                
                if ($stmt->rowCount() > 0) {
                    $success = "Tax rate deleted successfully!";
                    // Refresh the page to show updated list
                    header("Location: taxes.php?success=" . urlencode($success));
                    exit();
                } else {
                    $errors[] = "Tax rate not found or already deleted.";
                }
            }
        } catch (PDOException $e) {
            $errors[] = "Error deleting tax rate: " . $e->getMessage();
            error_log("Tax delete error: " . $e->getMessage());
        }
    } 
    elseif (isset($_POST['action'])) {
        // Handle add or edit
        $action = $_POST['action'];
        
        $cgst_rate = trim($_POST['cgst_rate'] ?? '');
        $sgst_rate = trim($_POST['sgst_rate'] ?? '');
        $effective_date = $_POST['effective_date'] ?? '';
        $tax_id = isset($_POST['tax_id']) ? (int)$_POST['tax_id'] : 0;

        // Debug: Check what values we're receiving
        error_log("Action: $action, CGST: $cgst_rate, SGST: $sgst_rate, Date: $effective_date, Tax ID: $tax_id");

        // Validate inputs
        if (!is_numeric($cgst_rate) || $cgst_rate < 0 || $cgst_rate > 100) {
            $errors[] = "CGST rate must be a non-negative number between 0 and 100.";
        }
        
        if (!is_numeric($sgst_rate) || $sgst_rate < 0 || $sgst_rate > 100) {
            $errors[] = "SGST rate must be a non-negative number between 0 and 100.";
        }
        
        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. Use YYYY-MM-DD.";
            } 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 (only if validation passed)
        if (empty($errors)) {
            try {
                $check_query = "
                    SELECT COUNT(*) FROM taxes 
                    WHERE effective_date = :effective_date 
                    AND tax_id != :tax_id
                ";
                $stmt = $pdo->prepare($check_query);
                $stmt->execute([
                    'effective_date' => $effective_date,
                    'tax_id' => $action === 'edit' ? $tax_id : 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();
                error_log("Date check error: " . $e->getMessage());
            }
        }

        // Perform add or edit if no errors
        if (empty($errors)) {
            try {
                if ($action === 'add') {
                    $stmt = $pdo->prepare("
                        INSERT INTO taxes (branch_id, cgst_rate, sgst_rate, effective_date, created_at)
                        VALUES (:branch_id, :cgst_rate, :sgst_rate, :effective_date, NOW())
                    ");
                    
                    // Use branch_id = 1 as default, or adjust based on your needs
                    $result = $stmt->execute([
                        'branch_id' => 1, // Default branch, adjust as needed
                        'cgst_rate' => $cgst_rate,
                        'sgst_rate' => $sgst_rate,
                        'effective_date' => $effective_date
                    ]);
                    
                    if ($result) {
                        $success = "Tax rate added successfully!";
                        // Clear form fields
                        $cgst_rate = $sgst_rate = $effective_date = '';
                        // Refresh to show new data
                        header("Location: taxes.php?success=" . urlencode($success));
                        exit();
                    } else {
                        $errors[] = "Failed to add tax rate.";
                    }
                    
                } elseif ($action === 'edit' && $tax_id > 0) {
                    $stmt = $pdo->prepare("
                        UPDATE taxes 
                        SET cgst_rate = :cgst_rate, sgst_rate = :sgst_rate, effective_date = :effective_date
                        WHERE tax_id = :tax_id
                    ");
                    
                    $result = $stmt->execute([
                        'cgst_rate' => $cgst_rate,
                        'sgst_rate' => $sgst_rate,
                        'effective_date' => $effective_date,
                        'tax_id' => $tax_id
                    ]);
                    
                    if ($result && $stmt->rowCount() > 0) {
                        $success = "Tax rate updated successfully!";
                        // Clear form and exit edit mode
                        $cgst_rate = $sgst_rate = $effective_date = '';
                        $edit_tax_id = null;
                        // Refresh to show updated data
                        header("Location: taxes.php?success=" . urlencode($success));
                        exit();
                    } else {
                        $errors[] = "Tax rate not found or no changes made.";
                    }
                }
            } catch (PDOException $e) {
                $errors[] = "Error saving tax rate: " . $e->getMessage();
                error_log("Tax save error: " . $e->getMessage());
                
                // Check for specific MySQL errors
                if ($e->errorInfo[1] == 1062) {
                    $errors[] = "A tax rate with this effective date already exists.";
                }
            }
        }
    }
}

// Check for success message from redirect
if (isset($_GET['success'])) {
    $success = urldecode($_GET['success']);
}

// Fetch tax rate for editing
if (isset($_GET['edit'])) {
    $edit_tax_id = (int)$_GET['edit'];
    try {
        $stmt = $pdo->prepare("
            SELECT tax_id, cgst_rate, sgst_rate, effective_date
            FROM taxes 
            WHERE tax_id = :tax_id
        ");
        $stmt->execute(['tax_id' => $edit_tax_id]);
        $tax = $stmt->fetch(PDO::FETCH_ASSOC);
        
        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();
        error_log("Tax edit fetch error: " . $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; }

/* Debug styles */
.debug-info {
    background: #f8f9fa;
    border-left: 4px solid #dc3545;
    padding: 10px;
    margin: 10px 0;
    font-size: 0.8rem;
}
</style>
<!-- Font Awesome 6 Free -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css" crossorigin="anonymous" referrerpolicy="no-referrer" />
<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>

    <!-- Debug information (remove in production) -->
    <?php if (isset($_POST) && !empty($_POST)): ?>
    <div class="debug-info">
        <strong>POST Data:</strong><br>
        <?php foreach ($_POST as $key => $value): ?>
            <?= htmlspecialchars($key) ?>: <?= htmlspecialchars($value) ?><br>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>

    <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">
                    <i class="fas fa-check-circle me-2"></i>
                    <?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">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <strong>Please fix the following errors:</strong>
                    <ul class="mb-0 mt-2">
                        <?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" id="taxForm">
                <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" max="100" class="form-control bg-base" id="cgst_rate" name="cgst_rate" 
                               value="<?php echo htmlspecialchars($cgst_rate); ?>" required
                               placeholder="0.00">
                        <div class="form-text">Enter CGST percentage (0-100)</div>
                    </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" max="100" class="form-control bg-base" id="sgst_rate" name="sgst_rate" 
                               value="<?php echo htmlspecialchars($sgst_rate); ?>" required
                               placeholder="0.00">
                        <div class="form-text">Enter SGST percentage (0-100)</div>
                    </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
                               min="<?php echo $edit_tax_id ? '' : date('Y-m-d'); ?>">
                        <div class="form-text">
                            <?php echo $edit_tax_id ? 'Date when this rate becomes effective' : 'Must be today or future date'; ?>
                        </div>
                    </div>
                    <div class="col-md-3 d-flex align-items-end">
                        <div class="w-100">
                            <button type="submit" class="btn btn-primary bg-primary-600 hover-bg-primary-700 text-white w-100">
                                <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 w-100 mt-2">
                                    <i class="fas fa-times fa-icon"></i> Cancel
                                </a>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Rest of your HTML remains the same -->
    <!-- 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">ID</th>
                                <th scope="col">CGST Rate (%)</th>
                                <th scope="col">SGST Rate (%)</th>
                                <th scope="col">Total (%)</th>
                                <th scope="col">Effective Date</th>
                                <th scope="col">Status</th>
                                <th scope="col" class="text-center">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($taxes)): ?>
                                <tr>
                                    <td colspan="7" class="text-sm text-center">
                                        <div class="d-flex flex-column align-items-center py-4">
                                            <i class="fas fa-percent text-3xl text-secondary mb-2"></i>
                                            <span>No tax rates found</span>
                                            <small class="text-muted">Add your first tax rate using the form above</small>
                                        </div>
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($taxes as $tax): 
                                    $is_current = $tax['effective_date'] <= date('Y-m-d');
                                    $is_future = $tax['effective_date'] > date('Y-m-d');
                                ?>
                                    <tr>
                                        <td class="fw-bold">#<?php echo $tax['tax_id']; ?></td>
                                        <td><?php echo number_format($tax['cgst_rate'], 2); ?>%</td>
                                        <td><?php echo number_format($tax['sgst_rate'], 2); ?>%</td>
                                        <td class="fw-bold text-primary"><?php echo number_format($tax['cgst_rate'] + $tax['sgst_rate'], 2); ?>%</td>
                                        <td>
                                            <?php echo date('d M Y', strtotime($tax['effective_date'])); ?>
                                            <?php if ($is_future): ?>
                                                <br><small class="text-warning">Upcoming</small>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($is_current): ?>
                                                <span class="badge bg-success">Active</span>
                                            <?php else: ?>
                                                <span class="badge bg-warning">Future</span>
                                            <?php endif; ?>
                                        </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="btn btn-sm btn-outline-primary"
                                                   title="Edit">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                <?php if ($is_future): ?>
                                                <form action="taxes.php" method="POST" style="display:inline;" 
                                                      onsubmit="return confirm('Are you sure you want to delete tax rate #<?php echo $tax['tax_id']; ?>?');">
                                                    <input type="hidden" name="delete_tax_id" value="<?php echo $tax['tax_id']; ?>">
                                                    <button type="submit" class="btn btn-sm btn-outline-danger" title="Delete">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </form>
                                                <?php else: ?>
                                                <button class="btn btn-sm btn-outline-secondary" disabled title="Cannot delete active tax rates">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                                <?php endif; ?>
                                            </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>
                            <small class="text-muted">Add your first tax rate using the form above</small>
                        </div>
                    </div>
                <?php else: ?>
                    <div class="row g-3">
                        <?php foreach ($taxes as $index => $tax): 
                            $is_current = $tax['effective_date'] <= date('Y-m-d');
                            $is_future = $tax['effective_date'] > date('Y-m-d');
                        ?>
                            <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 $tax['tax_id']; ?>
                                            </h6>
                                            <span class="badge <?php echo $is_current ? 'bg-success' : 'bg-warning'; ?>">
                                                <?php echo $is_current ? 'Active' : 'Future'; ?>
                                            </span>
                                        </div>
                                        <div class="mb-2">
                                            <p class="text-sm mb-1">
                                                <strong><i class="fas fa-percentage fa-icon"></i> CGST:</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:</strong> <?php echo number_format($tax['sgst_rate'], 2); ?>%
                                            </p>
                                            <p class="text-sm mb-1">
                                                <strong>Total GST:</strong> 
                                                <span class="fw-bold text-primary"><?php echo number_format($tax['cgst_rate'] + $tax['sgst_rate'], 2); ?>%</span>
                                            </p>
                                            <p class="text-sm mb-1">
                                                <strong><i class="fas fa-calendar-alt fa-icon"></i> Effective:</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-primary">
                                                    <i class="fas fa-edit fa-icon"></i> Edit
                                                </a>
                                                <?php if ($is_future): ?>
                                                <form action="taxes.php" method="POST" style="display:inline;" 
                                                      onsubmit="return confirm('Delete tax rate #<?php echo $tax['tax_id']; ?>?');">
                                                    <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>
                                                <?php else: ?>
                                                <button class="btn btn-sm btn-outline-secondary" disabled title="Cannot delete active rates">
                                                    <i class="fas fa-trash fa-icon"></i> Delete
                                                </button>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
// Client-side validation
document.getElementById('taxForm').addEventListener('submit', function(e) {
    const cgst = document.getElementById('cgst_rate').value;
    const sgst = document.getElementById('sgst_rate').value;
    const effectiveDate = document.getElementById('effective_date').value;
    
    let errors = [];
    
    if (cgst < 0 || cgst > 100) {
        errors.push('CGST rate must be between 0 and 100');
    }
    
    if (sgst < 0 || sgst > 100) {
        errors.push('SGST rate must be between 0 and 100');
    }
    
    if (!effectiveDate) {
        errors.push('Effective date is required');
    }
    
    if (errors.length > 0) {
        e.preventDefault();
        alert('Please fix the following errors:\n\n' + errors.join('\n'));
    }
});
</script>

<?php include './partials/layouts/layoutBottom.php' ?>