<?php
ob_start();
include 'db.php';
include 'layout.php';
include 'financial_helpers.php';

$store_id = $_SESSION['store_id'] ?? 1;

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add_period':
                $period_name = $_POST['period_name'];
                $start_date = $_POST['start_date'];
                $end_date = $_POST['end_date'];
                
                $stmt = $conn->prepare("
                    INSERT INTO fiscal_periods (period_name, start_date, end_date, is_closed) 
                    VALUES (?, ?, ?, 0)
                ");
                $stmt->bind_param("sss", $period_name, $start_date, $end_date);
                
                if ($stmt->execute()) {
                    $success_message = "Financial period created successfully!";
                } else {
                    $error_message = "Error creating financial period.";
                }
                break;
                
            case 'close_period':
                $period_id = $_POST['period_id'];
                
                                 // Check if period has any unposted journal entries
                 $stmt = $conn->prepare("
                     SELECT COUNT(*) as unposted_count 
                     FROM journal_entries je 
                     WHERE je.entry_date BETWEEN 
                         (SELECT start_date FROM fiscal_periods WHERE id = ?) 
                     AND 
                         (SELECT end_date FROM fiscal_periods WHERE id = ?)
                     AND je.status = 'draft'
                 ");
                 $stmt->bind_param("ii", $period_id, $period_id);
                $stmt->execute();
                $result = $stmt->get_result()->fetch_assoc();
                
                if ($result['unposted_count'] > 0) {
                    $error_message = "Cannot close period. There are " . $result['unposted_count'] . " unposted journal entries.";
                } else {
                                         $stmt = $conn->prepare("UPDATE fiscal_periods SET is_closed = 1, closed_at = NOW() WHERE id = ?");
                     $stmt->bind_param("i", $period_id);
                    
                    if ($stmt->execute()) {
                        $success_message = "Financial period closed successfully!";
                    } else {
                        $error_message = "Error closing financial period.";
                    }
                }
                break;
        }
    }
}

// Get fiscal periods for display (if table exists)
$fiscal_periods = null;
$current_period = null;

try {
         $stmt = $conn->prepare("
         SELECT 
             fp.*,
             COUNT(je.id) as journal_entries_count,
             SUM(CASE WHEN je.status = 'posted' THEN 1 ELSE 0 END) as posted_entries,
             SUM(CASE WHEN je.status = 'draft' THEN 1 ELSE 0 END) as draft_entries
         FROM fiscal_periods fp
         LEFT JOIN journal_entries je ON je.entry_date BETWEEN fp.start_date AND fp.end_date
         GROUP BY fp.id
         ORDER BY fp.start_date DESC
     ");
    $stmt->execute();
    $fiscal_periods = $stmt->get_result();

         // Get current period info
     $stmt = $conn->prepare("
         SELECT * FROM fiscal_periods 
         WHERE is_closed = 0 
         AND start_date <= CURDATE() AND end_date >= CURDATE()
         ORDER BY start_date DESC LIMIT 1
     ");
    $stmt->execute();
    $current_period = $stmt->get_result()->fetch_assoc();
} catch (Exception $e) {
    // Table doesn't exist yet, that's okay
    $fiscal_periods = null;
    $current_period = null;
}
?>

<div class="page-wrapper">
    <div class="content">
        <?php if (isset($success_message)): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fa fa-check-circle"></i> <?php echo htmlspecialchars($success_message); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <?php if (isset($error_message)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fa fa-exclamation-triangle"></i> <?php echo htmlspecialchars($error_message); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <div class="page-header">
            <div class="page-title">
                <h4>Financial Periods</h4>
                <h6>Manage fiscal periods and accounting cycles</h6>
            </div>
            <div class="page-btn">
                <button class="btn btn-added" data-bs-toggle="modal" data-bs-target="#addPeriodModal">
                    <i class="fa fa-plus"></i> Add Period
                </button>
            </div>
        </div>

        <!-- Current Period Info -->
        <?php if ($current_period): ?>
            <div class="card">
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <h5><i class="fa fa-calendar-check text-success"></i> Current Period</h5>
                            <table class="table table-borderless">
                                <tr>
                                    <td><strong>Period:</strong></td>
                                    <td><?php echo htmlspecialchars($current_period['period_name']); ?></td>
                                </tr>
                                <tr>
                                    <td><strong>Date Range:</strong></td>
                                    <td><?php echo date('M j, Y', strtotime($current_period['start_date'])); ?> - <?php echo date('M j, Y', strtotime($current_period['end_date'])); ?></td>
                                </tr>
                                <tr>
                                    <td><strong>Status:</strong></td>
                                    <td><span class="badge bg-success">Open</span></td>
                                </tr>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <h5><i class="fa fa-chart-bar text-info"></i> Period Summary</h5>
                            <table class="table table-borderless">
                                <tr>
                                    <td><strong>Total Entries:</strong></td>
                                    <td><?php echo $current_period['journal_entries_count'] ?? 0; ?></td>
                                </tr>
                                <tr>
                                    <td><strong>Posted Entries:</strong></td>
                                    <td><span class="text-success"><?php echo $current_period['posted_entries'] ?? 0; ?></span></td>
                                </tr>
                                <tr>
                                    <td><strong>Draft Entries:</strong></td>
                                    <td><span class="text-warning"><?php echo $current_period['draft_entries'] ?? 0; ?></span></td>
                                </tr>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <!-- Fiscal Periods Table -->
        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table datatable">
                        <thead>
                            <tr>
                                <th>Period Name</th>
                                <th>Date Range</th>
                                <th>Status</th>
                                <th>Journal Entries</th>
                                <th>Posted</th>
                                <th>Draft</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($fiscal_periods && $fiscal_periods->num_rows > 0): ?>
                                <?php while ($period = $fiscal_periods->fetch_assoc()): ?>
                                    <tr>
                                        <td>
                                            <strong><?php echo htmlspecialchars($period['period_name']); ?></strong>
                                        </td>
                                        <td>
                                            <?php echo date('M j, Y', strtotime($period['start_date'])); ?> - 
                                            <?php echo date('M j, Y', strtotime($period['end_date'])); ?>
                                        </td>
                                                                                 <td>
                                             <?php if ($period['is_closed'] == 0): ?>
                                                 <span class="badge bg-success">Open</span>
                                             <?php else: ?>
                                                 <span class="badge bg-secondary">Closed</span>
                                                 <?php if ($period['closed_at']): ?>
                                                     <br><small class="text-muted"><?php echo date('M j, Y', strtotime($period['closed_at'])); ?></small>
                                                 <?php endif; ?>
                                             <?php endif; ?>
                                         </td>
                                        <td><?php echo $period['journal_entries_count'] ?? 0; ?></td>
                                        <td><span class="text-success"><?php echo $period['posted_entries'] ?? 0; ?></span></td>
                                        <td><span class="text-warning"><?php echo $period['draft_entries'] ?? 0; ?></span></td>
                                                                                 <td>
                                             <?php if ($period['is_closed'] == 0): ?>
                                                 <button class="btn btn-sm btn-outline-warning" onclick="closePeriod(<?php echo $period['id']; ?>, '<?php echo htmlspecialchars($period['period_name']); ?>')">
                                                     <i class="fa fa-lock"></i> Close
                                                 </button>
                                             <?php else: ?>
                                                 <span class="text-muted">No actions</span>
                                             <?php endif; ?>
                                         </td>
                                    </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td class="text-center text-muted">
                                        <i class="fa fa-calendar-times"></i> No financial periods found. 
                                        Click "Add Period" to create your first period.
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Period Modal -->
<div class="modal fade" id="addPeriodModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add Financial Period</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="add_period">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="period_name" class="form-label">Period Name *</label>
                        <input type="text" class="form-control" id="period_name" name="period_name" required 
                               placeholder="e.g., Q1 2024, January 2024">
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="start_date" class="form-label">Start Date *</label>
                                <input type="date" class="form-control" id="start_date" name="start_date" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="end_date" class="form-label">End Date *</label>
                                <input type="date" class="form-control" id="end_date" name="end_date" required>
                            </div>
                        </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">Create Period</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function closePeriod(periodId, periodName) {
    if (confirm(`Are you sure you want to close the period "${periodName}"? This action cannot be undone.`)) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.innerHTML = `
            <input type="hidden" name="action" value="close_period">
            <input type="hidden" name="period_id" value="${periodId}">
        `;
        document.body.appendChild(form);
        form.submit();
    }
}

// Set default dates for new period
document.addEventListener('DOMContentLoaded', function() {
    const today = new Date();
    const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
    const endOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0);
    
    document.getElementById('start_date').value = startOfMonth.toISOString().split('T')[0];
    document.getElementById('end_date').value = endOfMonth.toISOString().split('T')[0];
});
</script>

</body>
</html>
