<?php
/**
 * Enterprise HRM ERP System - Fortnight Stock Report View
 * Month/Year wise report viewing - Modern UI Design
 */

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

$pageTitle = 'Fortnight Stock Report';
$currentModule = 'fortnight';

$siteId = getCurrentSiteId();
$selectedMonth = isset($_GET['month']) ? (int)$_GET['month'] : (int)date('m');
$selectedYear = isset($_GET['year']) ? (int)$_GET['year'] : (int)date('Y');

// Validate
if ($selectedMonth < 1 || $selectedMonth > 12) $selectedMonth = (int)date('m');
if ($selectedYear < 2020 || $selectedYear > 2100) $selectedYear = (int)date('Y');

// Handle delete request
if (isset($_GET['delete']) && $_GET['delete'] > 0) {
    $deletePeriodId = (int)$_GET['delete'];
    try {
        $db = getDB();
        $db->beginTransaction();
        $stmt = $db->prepare("SELECT period_id, period_name FROM fortnight_periods WHERE period_id = ? AND site_id = ?");
        $stmt->execute([$deletePeriodId, $siteId]);
        $periodToDelete = $stmt->fetch();
        if (!$periodToDelete) throw new Exception('Period not found.');
        $stmt = $db->prepare("DELETE FROM fortnight_inventory WHERE period_id = ?");
        $stmt->execute([$deletePeriodId]);
        $stmt = $db->prepare("DELETE FROM fortnight_periods WHERE period_id = ? AND site_id = ?");
        $stmt->execute([$deletePeriodId, $siteId]);
        $db->commit();
        $_SESSION['success'] = 'Report deleted successfully.';
        header('Location: ' . $_SERVER['PHP_SELF'] . '?month=' . $selectedMonth . '&year=' . $selectedYear);
        exit;
    } catch (Exception $e) {
        if (isset($db) && $db->inTransaction()) $db->rollBack();
        $_SESSION['error'] = 'Error: ' . $e->getMessage();
        header('Location: ' . $_SERVER['PHP_SELF'] . '?month=' . $selectedMonth . '&year=' . $selectedYear);
        exit;
    }
}

try {
    $db = getDB();
    $stmt = $db->prepare("
        SELECT DISTINCT p.period_id, p.period_name, p.date as start_date, p.period_date as end_date,
               p.month, p.year, p.site_id, p.created_by, p.created_at,
               COUNT(DISTINCT CASE WHEN fi.row_type = 'data' THEN fi.inventory_id END) as item_count,
               COALESCE(SUM(CASE WHEN fi.row_type = 'data' THEN fi.opening_stock_value ELSE 0 END), 0) as total_opening_value,
               COALESCE(SUM(CASE WHEN fi.row_type = 'data' THEN fi.purchase_value ELSE 0 END), 0) as total_purchase_value,
               COALESCE(SUM(CASE WHEN fi.row_type = 'data' THEN fi.consumption_value ELSE 0 END), 0) as total_consumption_value,
               COALESCE(SUM(CASE WHEN fi.row_type = 'data' THEN fi.closing_stock_value ELSE 0 END), 0) as total_closing_value
        FROM fortnight_periods p
        LEFT JOIN fortnight_inventory fi ON p.period_id = fi.period_id
        WHERE p.site_id = ? AND MONTH(p.date) = ? AND YEAR(p.date) = ?
        GROUP BY p.period_id
        ORDER BY p.period_id DESC
    ");
    $stmt->execute([$siteId, $selectedMonth, $selectedYear]);
    $periods = $stmt->fetchAll();
    
    $uniquePeriods = [];
    $seenPeriodIds = [];
    foreach ($periods as $period) {
        if (!in_array($period['period_id'], $seenPeriodIds)) {
            $uniquePeriods[] = $period;
            $seenPeriodIds[] = $period['period_id'];
        }
    }
    $periods = $uniquePeriods;
} catch (Exception $e) {
    error_log("Report error: " . $e->getMessage());
    $periods = [];
}

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

<style>
/* ========== MODERN REPORT UI STYLES ========== */
:root {
    --primary: #667eea;
    --primary-dark: #5a67d8;
    --secondary: #764ba2;
    --success: #48bb78;
    --success-dark: #38a169;
    --info: #4299e1;
    --warning: #ed8936;
    --danger: #f56565;
    --dark: #2d3748;
    --light: #f7fafc;
    --gradient-primary: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    --gradient-success: linear-gradient(135deg, #48bb78 0%, #38a169 100%);
    --gradient-info: linear-gradient(135deg, #4299e1 0%, #3182ce 100%);
    --gradient-warning: linear-gradient(135deg, #ed8936 0%, #dd6b20 100%);
    --gradient-danger: linear-gradient(135deg, #f56565 0%, #e53e3e 100%);
    --shadow-sm: 0 2px 4px rgba(0,0,0,0.05);
    --shadow-md: 0 4px 12px rgba(0,0,0,0.1);
    --shadow-lg: 0 10px 40px rgba(0,0,0,0.15);
    --radius-sm: 8px;
    --radius-md: 12px;
    --radius-lg: 16px;
}

.report-container {
    background: linear-gradient(135deg, #f0f4f8 0%, #e2e8f0 100%);
    padding: 30px;
    margin: 15px;
    border-radius: var(--radius-lg);
    box-shadow: var(--shadow-lg);
    font-family: 'Segoe UI', -apple-system, BlinkMacSystemFont, sans-serif;
    min-height: calc(100vh - 100px);
}

.report-header {
    background: var(--gradient-primary);
    color: #fff;
    padding: 25px 30px;
    margin: -30px -30px 30px -30px;
    border-radius: var(--radius-lg) var(--radius-lg) 0 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 15px;
}

.report-header h2 {
    margin: 0;
    font-size: 26px;
    font-weight: 700;
    display: flex;
    align-items: center;
    gap: 12px;
    text-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.report-header h2::before {
    content: '📊';
    font-size: 32px;
}
</style>

<style>
/* Filter Section */
.filter-card {
    background: #fff;
    padding: 20px 25px;
    margin-bottom: 25px;
    border-radius: var(--radius-md);
    box-shadow: var(--shadow-md);
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    align-items: center;
    border-left: 5px solid var(--primary);
}

.filter-group {
    display: flex;
    align-items: center;
    gap: 10px;
}

.filter-group label {
    font-weight: 600;
    color: var(--dark);
    font-size: 14px;
    white-space: nowrap;
}

.filter-group select, .filter-group input {
    padding: 10px 16px;
    border: 2px solid #e2e8f0;
    border-radius: var(--radius-sm);
    font-size: 14px;
    transition: all 0.3s ease;
    background: #fff;
    min-width: 120px;
}

.filter-group select:focus, .filter-group input:focus {
    outline: none;
    border-color: var(--primary);
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2);
}

/* Buttons */
.btn {
    padding: 10px 20px;
    border-radius: var(--radius-sm);
    font-weight: 600;
    font-size: 13px;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    transition: all 0.3s ease;
    cursor: pointer;
    border: none;
    box-shadow: var(--shadow-sm);
}

.btn:hover { transform: translateY(-2px); box-shadow: var(--shadow-md); }
.btn-primary { background: var(--gradient-primary); color: #fff; }
.btn-success { background: var(--gradient-success); color: #fff; }
.btn-info { background: var(--gradient-info); color: #fff; }
.btn-warning { background: var(--gradient-warning); color: #fff; }
.btn-danger { background: var(--gradient-danger); color: #fff; }
.btn-secondary { background: linear-gradient(135deg, #718096 0%, #4a5568 100%); color: #fff; }
.btn-sm { padding: 6px 14px; font-size: 12px; }

/* Summary Cards */
.summary-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}

.summary-card {
    background: #fff;
    border-radius: var(--radius-md);
    padding: 20px;
    box-shadow: var(--shadow-md);
    position: relative;
    overflow: hidden;
    transition: transform 0.3s ease;
}

.summary-card:hover { transform: translateY(-5px); }

.summary-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
}

.summary-card.opening::before { background: var(--gradient-success); }
.summary-card.purchase::before { background: var(--gradient-info); }
.summary-card.consumption::before { background: var(--gradient-warning); }
.summary-card.closing::before { background: var(--gradient-danger); }

.summary-card .icon {
    width: 50px;
    height: 50px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    margin-bottom: 15px;
}

.summary-card.opening .icon { background: rgba(72, 187, 120, 0.15); }
.summary-card.purchase .icon { background: rgba(66, 153, 225, 0.15); }
.summary-card.consumption .icon { background: rgba(237, 137, 54, 0.15); }
.summary-card.closing .icon { background: rgba(245, 101, 101, 0.15); }

.summary-card .label { font-size: 13px; color: #718096; font-weight: 500; margin-bottom: 5px; }
.summary-card .value { font-size: 28px; font-weight: 700; color: var(--dark); }
.summary-card .qty { font-size: 14px; color: #a0aec0; margin-top: 5px; }
.summary-card.opening .value { color: var(--success); }
.summary-card.purchase .value { color: var(--info); }
.summary-card.consumption .value { color: var(--warning); }
.summary-card.closing .value { color: var(--danger); }
</style>

<style>
/* Period Cards */
.period-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}

.period-card {
    background: #fff;
    border-radius: var(--radius-md);
    box-shadow: var(--shadow-md);
    overflow: hidden;
    transition: all 0.3s ease;
}

.period-card:hover { transform: translateY(-5px); box-shadow: var(--shadow-lg); }

.period-card-header {
    background: var(--gradient-primary);
    color: #fff;
    padding: 15px 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.period-card-header h4 { margin: 0; font-size: 16px; font-weight: 600; }
.period-card-header .badge {
    background: rgba(255,255,255,0.2);
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
}

.period-card-body { padding: 20px; }

.period-info { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px; }
.period-info-item { }
.period-info-item .label { font-size: 12px; color: #718096; margin-bottom: 3px; }
.period-info-item .value { font-size: 14px; font-weight: 600; color: var(--dark); }

.period-stats { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; padding-top: 15px; border-top: 1px solid #e2e8f0; }
.period-stat { text-align: center; padding: 10px; background: #f7fafc; border-radius: var(--radius-sm); }
.period-stat .label { font-size: 11px; color: #718096; }
.period-stat .value { font-size: 16px; font-weight: 700; }
.period-stat.opening .value { color: var(--success); }
.period-stat.closing .value { color: var(--danger); }

.period-card-footer { padding: 15px 20px; background: #f7fafc; display: flex; gap: 10px; flex-wrap: wrap; }

/* Modern Table */
.table-card {
    background: #fff;
    border-radius: var(--radius-md);
    box-shadow: var(--shadow-md);
    overflow: hidden;
    margin-bottom: 30px;
}

.table-card-header {
    background: var(--gradient-primary);
    color: #fff;
    padding: 18px 25px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.table-card-header h3 { margin: 0; font-size: 18px; font-weight: 600; display: flex; align-items: center; gap: 10px; }

.table-responsive { overflow-x: auto; }

.modern-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 13px;
}

.modern-table thead th {
    background: linear-gradient(135deg, #1e3a5f 0%, #2d4a6f 100%);
    color: #fff;
    padding: 14px 12px;
    text-align: center;
    font-weight: 600;
    font-size: 11px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    white-space: nowrap;
    border: 1px solid #1a3050;
}

.modern-table tbody td {
    padding: 12px;
    border: 1px solid #e2e8f0;
    vertical-align: middle;
}

.modern-table tbody tr:nth-child(even) { background: #f8fafc; }
.modern-table tbody tr:hover { background: #edf2f7; }

.modern-table .text-right { text-align: right; }
.modern-table .text-center { text-align: center; }

.modern-table .value-cell {
    background: linear-gradient(135deg, #e6fffa 0%, #c6f6d5 100%);
    font-weight: 600;
    color: #276749;
}

/* Header Row in Table */
.modern-table .header-row td {
    background: linear-gradient(135deg, #1e3a5f 0%, #2d4a6f 100%) !important;
    color: #fff !important;
    font-weight: 600;
    text-align: center;
    padding: 12px;
    font-size: 11px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

/* Calculation/Total Row */
.modern-table .calc-row td {
    background: linear-gradient(135deg, #f6ad55 0%, #ed8936 100%) !important;
    color: #000 !important;
    font-weight: 700;
    padding: 14px 12px;
    font-size: 13px;
}

/* Grand Total Row */
.modern-table .grand-total td {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
    color: #fff !important;
    font-weight: 700;
    padding: 16px 12px;
    font-size: 14px;
}
</style>

<style>
/* Alert Styles */
.alert {
    padding: 20px 25px;
    border-radius: var(--radius-md);
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    gap: 15px;
}

.alert-info {
    background: linear-gradient(135deg, #ebf8ff 0%, #bee3f8 100%);
    border-left: 5px solid var(--info);
    color: #2c5282;
}

.alert-success {
    background: linear-gradient(135deg, #f0fff4 0%, #c6f6d5 100%);
    border-left: 5px solid var(--success);
    color: #276749;
}

.alert a { color: var(--primary); font-weight: 600; text-decoration: none; }
.alert a:hover { text-decoration: underline; }

/* Section Title */
.section-title {
    font-size: 20px;
    font-weight: 700;
    color: var(--dark);
    margin: 30px 0 20px 0;
    padding-left: 15px;
    border-left: 4px solid var(--primary);
    display: flex;
    align-items: center;
    gap: 10px;
}

/* Back Button */
.back-link {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 10px 20px;
    background: var(--gradient-primary);
    color: #fff;
    text-decoration: none;
    border-radius: var(--radius-sm);
    font-weight: 600;
    margin-bottom: 20px;
    transition: all 0.3s ease;
}

.back-link:hover { transform: translateX(-5px); box-shadow: var(--shadow-md); }

/* Print Styles */
@media print {
    .report-container { box-shadow: none; margin: 0; padding: 15px; }
    .filter-card, .back-link, .btn { display: none !important; }
    .period-card-footer { display: none !important; }
    .modern-table { font-size: 10px; }
    .modern-table thead th, .modern-table tbody td { padding: 6px 4px; }
}

/* Responsive */
@media (max-width: 768px) {
    .report-container { padding: 15px; margin: 10px; }
    .report-header { padding: 15px 20px; margin: -15px -15px 20px -15px; }
    .report-header h2 { font-size: 20px; }
    .filter-card { flex-direction: column; align-items: stretch; }
    .summary-grid { grid-template-columns: 1fr 1fr; }
    .period-grid { grid-template-columns: 1fr; }
}
</style>

<div class="report-container">
    <div class="report-header">
        <h2>Fortnight Stock Reports</h2>
        <div style="display: flex; gap: 10px;">
            <a href="<?php echo BASE_URL; ?>/modules/fortnight/list.php" class="btn btn-secondary">
                ← Back to Entry
            </a>
        </div>
    </div>
    
    <!-- Filter Section -->
    <div class="filter-card">
        <div class="filter-group">
            <label>📅 Month:</label>
            <select id="filter_month" onchange="filterReport()">
                <?php for ($m = 1; $m <= 12; $m++): ?>
                <option value="<?php echo $m; ?>" <?php echo $m == $selectedMonth ? 'selected' : ''; ?>>
                    <?php echo date('F', mktime(0, 0, 0, $m, 1)); ?>
                </option>
                <?php endfor; ?>
            </select>
        </div>
        <div class="filter-group">
            <label>📆 Year:</label>
            <input type="number" id="filter_year" value="<?php echo $selectedYear; ?>" 
                   min="2020" max="2100" onchange="filterReport()" style="width: 100px;">
        </div>
        <button onclick="window.location.href='?month=<?php echo date('m'); ?>&year=<?php echo date('Y'); ?>'" class="btn btn-info btn-sm">
            🔄 Current Month
        </button>
        <button onclick="exportToExcel()" class="btn btn-success btn-sm">
            <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>
            Export Excel
        </button>
        <button onclick="window.print()" class="btn btn-secondary btn-sm">
            🖨️ Print Report
        </button>
    </div>
    
    <?php if (empty($periods)): ?>
    <div class="alert alert-info">
        <span style="font-size: 24px;">📭</span>
        <div>
            <strong>No reports found</strong> for <?php echo date('F Y', mktime(0, 0, 0, $selectedMonth, 1, $selectedYear)); ?>.
            <br><a href="<?php echo BASE_URL; ?>/modules/fortnight/list.php?month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>">
                Click here to create a new period →
            </a>
        </div>
    </div>
    <?php else: ?>
    
    <h3 class="section-title">📋 Reports for <?php echo date('F Y', mktime(0, 0, 0, $selectedMonth, 1, $selectedYear)); ?></h3>
    
    <!-- Period Cards -->
    <div class="period-grid">
        <?php foreach ($periods as $period): ?>
        <div class="period-card">
            <div class="period-card-header">
                <h4><?php echo htmlspecialchars($period['period_name'] ?: 'Stock Entry'); ?></h4>
                <span class="badge"><?php echo $period['item_count']; ?> Items</span>
            </div>
            <div class="period-card-body">
                <div class="period-info">
                    <div class="period-info-item">
                        <div class="label">From Date</div>
                        <div class="value"><?php echo date('d M Y', strtotime($period['start_date'])); ?></div>
                    </div>
                    <div class="period-info-item">
                        <div class="label">To Date</div>
                        <div class="value"><?php echo date('d M Y', strtotime($period['end_date'])); ?></div>
                    </div>
                </div>
                <div class="period-stats">
                    <div class="period-stat opening">
                        <div class="label">Opening Value</div>
                        <div class="value">₹<?php echo number_format($period['total_opening_value'], 0); ?></div>
                    </div>
                    <div class="period-stat closing">
                        <div class="label">Closing Value</div>
                        <div class="value">₹<?php echo number_format($period['total_closing_value'], 0); ?></div>
                    </div>
                </div>
            </div>
            <div class="period-card-footer">
                <a href="?view=<?php echo $period['period_id']; ?>&month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" class="btn btn-success btn-sm">👁️ View</a>
                <a href="<?php echo BASE_URL; ?>/modules/fortnight/list.php?period_id=<?php echo $period['period_id']; ?>" class="btn btn-warning btn-sm">✏️ Edit</a>
                <a href="<?php echo BASE_URL; ?>/modules/fortnight/export.php?period_id=<?php echo $period['period_id']; ?>" class="btn btn-info btn-sm">📥 Export</a>
                <a href="?delete=<?php echo $period['period_id']; ?>&month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
                   class="btn btn-danger btn-sm" onclick="return confirm('Delete this report?\n\n<?php echo addslashes($period['period_name']); ?>\n\nThis cannot be undone!');">🗑️ Delete</a>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>

    <?php
    // Detailed View Section
    if (isset($_GET['view']) && $_GET['view'] > 0):
        $viewPeriodId = (int)$_GET['view'];
        $stmt = $db->prepare("SELECT *, date as start_date, period_date as end_date FROM fortnight_periods WHERE period_id = ? AND site_id = ?");
        $stmt->execute([$viewPeriodId, $siteId]);
        $viewPeriod = $stmt->fetch();
        
        if ($viewPeriod):
            $stmt = $db->prepare("SELECT * FROM fortnight_inventory WHERE period_id = ? ORDER BY display_order ASC, inventory_id ASC");
            $stmt->execute([$viewPeriodId]);
            $viewItems = $stmt->fetchAll();
            
            // Calculate Grand Totals (only from data rows)
            $grandTotals = ['opening_qty' => 0, 'opening_value' => 0, 'purchase_qty' => 0, 'purchase_value' => 0, 
                           'consumption_qty' => 0, 'consumption_value' => 0, 'closing_qty' => 0, 'closing_value' => 0];
            foreach ($viewItems as $item) {
                if (($item['row_type'] ?? 'data') === 'data') {
                    $grandTotals['opening_qty'] += $item['opening_stock_qty'];
                    $grandTotals['opening_value'] += $item['opening_stock_value'];
                    $grandTotals['purchase_qty'] += $item['purchase_qty'];
                    $grandTotals['purchase_value'] += $item['purchase_value'];
                    $grandTotals['consumption_qty'] += $item['consumption_qty'];
                    $grandTotals['consumption_value'] += $item['consumption_value'];
                    $grandTotals['closing_qty'] += $item['closing_stock_qty'];
                    $grandTotals['closing_value'] += $item['closing_stock_value'];
                }
            }
    ?>
    
    <a href="?month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" class="back-link">
        ← Back to Reports List
    </a>
    
    <h3 class="section-title">📊 <?php echo htmlspecialchars($viewPeriod['period_name'] ?: 'Stock Report'); ?></h3>
    
    <!-- Summary Cards -->
    <div class="summary-grid">
        <div class="summary-card opening">
            <div class="icon">📦</div>
            <div class="label">Opening Stock</div>
            <div class="value">₹<?php echo number_format($grandTotals['opening_value'], 2); ?></div>
            <div class="qty">Qty: <?php echo number_format($grandTotals['opening_qty'], 3); ?></div>
        </div>
        <div class="summary-card purchase">
            <div class="icon">🛒</div>
            <div class="label">Total Purchase</div>
            <div class="value">₹<?php echo number_format($grandTotals['purchase_value'], 2); ?></div>
            <div class="qty">Qty: <?php echo number_format($grandTotals['purchase_qty'], 3); ?></div>
        </div>
        <div class="summary-card consumption">
            <div class="icon">📤</div>
            <div class="label">Total Consumption</div>
            <div class="value">₹<?php echo number_format($grandTotals['consumption_value'], 2); ?></div>
            <div class="qty">Qty: <?php echo number_format($grandTotals['consumption_qty'], 3); ?></div>
        </div>
        <div class="summary-card closing">
            <div class="icon">📋</div>
            <div class="label">Closing Stock</div>
            <div class="value">₹<?php echo number_format($grandTotals['closing_value'], 2); ?></div>
            <div class="qty">Qty: <?php echo number_format($grandTotals['closing_qty'], 3); ?></div>
        </div>
    </div>
    
    <!-- Period Info -->
    <div style="background: #fff; padding: 20px; border-radius: var(--radius-md); margin-bottom: 25px; box-shadow: var(--shadow-sm);">
        <div style="display: flex; flex-wrap: wrap; gap: 30px;">
            <div><strong>📅 Period:</strong> <?php echo date('d M Y', strtotime($viewPeriod['start_date'])); ?> to <?php echo date('d M Y', strtotime($viewPeriod['end_date'])); ?></div>
            <div><strong>📝 Name:</strong> <?php echo htmlspecialchars($viewPeriod['period_name'] ?: 'N/A'); ?></div>
            <div><strong>📊 Total Items:</strong> <?php echo count(array_filter($viewItems, fn($i) => ($i['row_type'] ?? 'data') === 'data')); ?></div>
        </div>
    </div>

    <!-- Detailed Table -->
    <div class="table-card">
        <div class="table-card-header">
            <h3>📋 Detailed Stock Report</h3>
            <a href="<?php echo BASE_URL; ?>/modules/fortnight/export.php?period_id=<?php echo $viewPeriodId; ?>" class="btn btn-info btn-sm">📥 Export Excel</a>
        </div>
        <div class="table-responsive">
            <table class="modern-table">
                <thead>
                    <tr>
                        <th style="width: 50px;">SR</th>
                        <th style="width: 120px;">HSN Code</th>
                        <th style="min-width: 200px;">Material Description</th>
                        <th style="width: 100px;">Net Rate</th>
                        <th style="width: 100px;">Opening Qty</th>
                        <th style="width: 120px;">Opening Value</th>
                        <th style="width: 100px;">Purchase Qty</th>
                        <th style="width: 120px;">Purchase Value</th>
                        <th style="width: 100px;">Consumption Qty</th>
                        <th style="width: 120px;">Consumption Value</th>
                        <th style="width: 100px;">Closing Qty</th>
                        <th style="width: 120px;">Closing Value</th>
                        <th style="width: 150px;">Supplier</th>
                        <th style="width: 120px;">Bill/Challan</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $rowNum = 0;
                    foreach ($viewItems as $item): 
                        $rowType = $item['row_type'] ?? 'data';
                        
                        if ($rowType === 'header'):
                    ?>
                    <tr class="header-row">
                        <td>SR</td>
                        <td>HSN Code</td>
                        <td><?php echo htmlspecialchars($item['header_text'] ?? 'Material Description'); ?></td>
                        <td>Net Rate</td>
                        <td>Opening Qty</td>
                        <td>Opening Value</td>
                        <td>Purchase Qty</td>
                        <td>Purchase Value</td>
                        <td>Consumption Qty</td>
                        <td>Consumption Value</td>
                        <td>Closing Qty</td>
                        <td>Closing Value</td>
                        <td>Supplier</td>
                        <td>Bill/Challan</td>
                    </tr>
                    <?php elseif ($rowType === 'calculation'): ?>
                    <tr class="calc-row">
                        <td colspan="3" class="text-center"><strong><?php echo htmlspecialchars($item['header_text'] ?? 'Total Amount'); ?></strong></td>
                        <td></td>
                        <td class="text-right"><?php echo number_format($item['opening_stock_qty'], 3); ?></td>
                        <td class="text-right"><?php echo number_format($item['opening_stock_value'], 2); ?></td>
                        <td class="text-right"><?php echo number_format($item['purchase_qty'], 3); ?></td>
                        <td class="text-right"><?php echo number_format($item['purchase_value'], 2); ?></td>
                        <td class="text-right"><?php echo number_format($item['consumption_qty'], 3); ?></td>
                        <td class="text-right"><?php echo number_format($item['consumption_value'], 2); ?></td>
                        <td class="text-right"><?php echo number_format($item['closing_stock_qty'], 3); ?></td>
                        <td class="text-right"><?php echo number_format($item['closing_stock_value'], 2); ?></td>
                        <td colspan="2"></td>
                    </tr>
                    <?php else: $rowNum++; ?>
                    <tr>
                        <td class="text-center"><?php echo $item['sr_no'] ?? $rowNum; ?></td>
                        <td><?php echo htmlspecialchars($item['material_hsn_code'] ?? ''); ?></td>
                        <td><?php echo htmlspecialchars($item['material_description']); ?></td>
                        <td class="text-right"><?php echo number_format($item['net_rate'], 2); ?></td>
                        <td class="text-right"><?php echo number_format($item['opening_stock_qty'], 3); ?></td>
                        <td class="text-right value-cell"><?php echo number_format($item['opening_stock_value'], 2); ?></td>
                        <td class="text-right"><?php echo number_format($item['purchase_qty'], 3); ?></td>
                        <td class="text-right value-cell"><?php echo number_format($item['purchase_value'], 2); ?></td>
                        <td class="text-right"><?php echo number_format($item['consumption_qty'], 3); ?></td>
                        <td class="text-right value-cell"><?php echo number_format($item['consumption_value'], 2); ?></td>
                        <td class="text-right"><?php echo number_format($item['closing_stock_qty'], 3); ?></td>
                        <td class="text-right value-cell"><?php echo number_format($item['closing_stock_value'], 2); ?></td>
                        <td><?php echo htmlspecialchars($item['supplier_name'] ?? ''); ?></td>
                        <td><?php echo htmlspecialchars($item['bill_challan_no'] ?? ''); ?></td>
                    </tr>
                    <?php endif; endforeach; ?>
                    
                    <!-- Grand Total Row -->
                    <tr class="grand-total">
                        <td colspan="3" class="text-center"><strong>🏆 GRAND TOTAL</strong></td>
                        <td></td>
                        <td class="text-right"><?php echo number_format($grandTotals['opening_qty'], 3); ?></td>
                        <td class="text-right">₹<?php echo number_format($grandTotals['opening_value'], 2); ?></td>
                        <td class="text-right"><?php echo number_format($grandTotals['purchase_qty'], 3); ?></td>
                        <td class="text-right">₹<?php echo number_format($grandTotals['purchase_value'], 2); ?></td>
                        <td class="text-right"><?php echo number_format($grandTotals['consumption_qty'], 3); ?></td>
                        <td class="text-right">₹<?php echo number_format($grandTotals['consumption_value'], 2); ?></td>
                        <td class="text-right"><?php echo number_format($grandTotals['closing_qty'], 3); ?></td>
                        <td class="text-right">₹<?php echo number_format($grandTotals['closing_value'], 2); ?></td>
                        <td colspan="2"></td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Stock Movement Analysis -->
    <div class="table-card">
        <div class="table-card-header" style="background: linear-gradient(135deg, #48bb78 0%, #38a169 100%);">
            <h3>📈 Stock Movement Analysis</h3>
        </div>
        <div style="padding: 25px;">
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px;">
                <!-- Stock Flow -->
                <div style="background: linear-gradient(135deg, #f0fff4 0%, #c6f6d5 100%); padding: 20px; border-radius: var(--radius-md);">
                    <h4 style="margin: 0 0 15px 0; color: #276749;">📊 Stock Flow Summary</h4>
                    <table style="width: 100%; font-size: 14px;">
                        <tr><td style="padding: 8px 0;">Opening Stock Value</td><td style="text-align: right; font-weight: 600; color: #276749;">₹<?php echo number_format($grandTotals['opening_value'], 2); ?></td></tr>
                        <tr><td style="padding: 8px 0; color: #2b6cb0;">+ Purchase Value</td><td style="text-align: right; font-weight: 600; color: #2b6cb0;">₹<?php echo number_format($grandTotals['purchase_value'], 2); ?></td></tr>
                        <tr style="border-top: 2px solid #9ae6b4;"><td style="padding: 8px 0; font-weight: 600;">= Total Available</td><td style="text-align: right; font-weight: 700; color: #276749;">₹<?php echo number_format($grandTotals['opening_value'] + $grandTotals['purchase_value'], 2); ?></td></tr>
                        <tr><td style="padding: 8px 0; color: #c05621;">- Consumption Value</td><td style="text-align: right; font-weight: 600; color: #c05621;">₹<?php echo number_format($grandTotals['consumption_value'], 2); ?></td></tr>
                        <tr style="border-top: 2px solid #9ae6b4; background: #c6f6d5;"><td style="padding: 12px 8px; font-weight: 700;">= Closing Stock Value</td><td style="text-align: right; font-weight: 700; font-size: 18px; color: #276749;">₹<?php echo number_format($grandTotals['closing_value'], 2); ?></td></tr>
                    </table>
                </div>
                
                <!-- Verification -->
                <div style="background: linear-gradient(135deg, #ebf8ff 0%, #bee3f8 100%); padding: 20px; border-radius: var(--radius-md);">
                    <h4 style="margin: 0 0 15px 0; color: #2c5282;">✅ Calculation Verification</h4>
                    <?php 
                    $calculatedClosing = $grandTotals['opening_value'] + $grandTotals['purchase_value'] - $grandTotals['consumption_value'];
                    $difference = abs($grandTotals['closing_value'] - $calculatedClosing);
                    $isMatch = $difference < 0.01;
                    ?>
                    <table style="width: 100%; font-size: 14px;">
                        <tr><td style="padding: 8px 0;">Expected Closing (O+P-C)</td><td style="text-align: right; font-weight: 600;">₹<?php echo number_format($calculatedClosing, 2); ?></td></tr>
                        <tr><td style="padding: 8px 0;">Actual Closing Value</td><td style="text-align: right; font-weight: 600;">₹<?php echo number_format($grandTotals['closing_value'], 2); ?></td></tr>
                        <tr style="border-top: 2px solid #90cdf4;">
                            <td style="padding: 12px 0; font-weight: 600;">Difference</td>
                            <td style="text-align: right; font-weight: 700; color: <?php echo $isMatch ? '#276749' : '#c53030'; ?>;">
                                <?php echo $isMatch ? '✅ Match' : '⚠️ ₹' . number_format($difference, 2); ?>
                            </td>
                        </tr>
                    </table>
                    <?php if ($isMatch): ?>
                    <div style="margin-top: 15px; padding: 10px; background: #c6f6d5; border-radius: 8px; text-align: center; color: #276749; font-weight: 600;">
                        ✅ All calculations are correct!
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Quantity Summary -->
            <div style="margin-top: 20px; background: #fff; padding: 20px; border-radius: var(--radius-md); border: 1px solid #e2e8f0;">
                <h4 style="margin: 0 0 15px 0; color: var(--dark);">📦 Quantity Summary</h4>
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px;">
                    <div style="text-align: center; padding: 15px; background: #f0fff4; border-radius: 8px;">
                        <div style="font-size: 12px; color: #718096;">Opening Qty</div>
                        <div style="font-size: 24px; font-weight: 700; color: #276749;"><?php echo number_format($grandTotals['opening_qty'], 3); ?></div>
                    </div>
                    <div style="text-align: center; padding: 15px; background: #ebf8ff; border-radius: 8px;">
                        <div style="font-size: 12px; color: #718096;">Purchase Qty</div>
                        <div style="font-size: 24px; font-weight: 700; color: #2b6cb0;"><?php echo number_format($grandTotals['purchase_qty'], 3); ?></div>
                    </div>
                    <div style="text-align: center; padding: 15px; background: #fffaf0; border-radius: 8px;">
                        <div style="font-size: 12px; color: #718096;">Consumption Qty</div>
                        <div style="font-size: 24px; font-weight: 700; color: #c05621;"><?php echo number_format($grandTotals['consumption_qty'], 3); ?></div>
                    </div>
                    <div style="text-align: center; padding: 15px; background: #fff5f5; border-radius: 8px;">
                        <div style="font-size: 12px; color: #718096;">Closing Qty</div>
                        <div style="font-size: 24px; font-weight: 700; color: #c53030;"><?php echo number_format($grandTotals['closing_qty'], 3); ?></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <?php 
        endif; // closes if ($viewPeriod)
    endif; // closes if (isset($_GET['view']))
    ?>
</div>

<script>
function filterReport() {
    const month = document.getElementById('filter_month').value;
    const year = document.getElementById('filter_year').value;
    window.location.href = '?month=' + month + '&year=' + year;
}

function exportToExcel() {
    const month = document.getElementById('filter_month').value;
    const year = document.getElementById('filter_year').value;
    window.location.href = '<?php echo BASE_URL; ?>/modules/fortnight/export.php?month=' + month + '&year=' + year;
}
</script>

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