<?php
declare(strict_types=1);

/**
 * ============================================================
 * PURE CHEMICAL - ADMIN DASHBOARD
 * File: admin/index.php
 * ============================================================
 */

session_start();

require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/auth.php';

$pdo = ($pdo instanceof PDO) ? $pdo : null;

$page_title = 'Dashboard';
$active_menu = 'dashboard';

/*
|--------------------------------------------------------------------------
| Dashboard Statistics
|--------------------------------------------------------------------------
| Existing tables se count liya ja raha hai.
| Agar kisi table mein data nahi hai to count 0 rahega.
|--------------------------------------------------------------------------
*/

function tableCount(?PDO $pdo, string $table): int
{
    if (!$pdo instanceof PDO) {
        return 0;
    }

    try {
        $allowedTables = [
            'products',
            'categories',
            'industries',
            'services',
            'brands',
            'blog_posts',
            'pages',
            'enquiries',
            'faqs',
            'testimonials',
            'galleries',
            'admins',
        ];

        if (!in_array($table, $allowedTables, true)) {
            return 0;
        }

        return (int) $pdo
            ->query("SELECT COUNT(*) FROM `{$table}`")
            ->fetchColumn();

    } catch (Throwable $e) {
        return 0;
    }
}

$stats = [
    'products'    => tableCount($pdo, 'products'),
    'categories'  => tableCount($pdo, 'categories'),
    'industries'  => tableCount($pdo, 'industries'),
    'services'    => tableCount($pdo, 'services'),
    'brands'      => tableCount($pdo, 'brands'),
    'blog_posts'  => tableCount($pdo, 'blog_posts'),
    'pages'       => tableCount($pdo, 'pages'),
    'enquiries'   => tableCount($pdo, 'enquiries'),
];

/*
|--------------------------------------------------------------------------
| Recent Enquiries
|--------------------------------------------------------------------------
*/

$recentEnquiries = [];

if ($pdo instanceof PDO) {
    try {

        $stmt = $pdo->query("
            SELECT
                id,
                name,
                email,
                created_at
            FROM enquiries
            ORDER BY id DESC
            LIMIT 5
        ");

        $recentEnquiries = $stmt instanceof PDOStatement ? $stmt->fetchAll() : [];

    } catch (Throwable $e) {
        $recentEnquiries = [];
    }
}

/*
|--------------------------------------------------------------------------
| Recent Products
|--------------------------------------------------------------------------
*/

$recentProducts = [];

if ($pdo instanceof PDO) {
    try {

        $stmt = $pdo->query("
            SELECT
                id,
                name,
                slug,
                status
            FROM products
            ORDER BY id DESC
            LIMIT 5
        ");

        $recentProducts = $stmt instanceof PDOStatement ? $stmt->fetchAll() : [];

    } catch (Throwable $e) {
        $recentProducts = [];
    }
}


/*
|--------------------------------------------------------------------------
| Admin Header
|--------------------------------------------------------------------------
*/

require_once __DIR__ . '/header.php';

?>

<style>

/* ============================================================
   DASHBOARD
============================================================ */

.dashboard-wrapper{
    max-width:1500px;
    margin:0 auto;
}


/* ============================================================
   PAGE HEADER
============================================================ */

.dashboard-header{
    display:flex;
    align-items:flex-end;
    justify-content:space-between;
    gap:20px;
    margin-bottom:28px;
}

.dashboard-heading h1{
    margin:0;
    font-size:28px;
    line-height:1.2;
    font-weight:800;
    color:#17202a;
}

.dashboard-heading p{
    margin:8px 0 0;
    color:#718096;
    font-size:13px;
}

.dashboard-date{
    padding:10px 14px;
    background:#fff;
    border:1px solid #e8edf2;
    border-radius:12px;
    color:#667085;
    font-size:12px;
    font-weight:600;
}


/* ============================================================
   STAT CARDS
============================================================ */

.dashboard-stats{
    display:grid;
    grid-template-columns:repeat(4, minmax(0,1fr));
    gap:18px;
    margin-bottom:28px;
}

.stat-card{
    position:relative;
    overflow:hidden;

    background:#fff;
    border:1px solid #e9eef2;
    border-radius:18px;

    padding:20px;

    box-shadow:
        0 8px 28px rgba(20,40,30,.045);

    transition:
        transform .22s ease,
        box-shadow .22s ease;
}

.stat-card:hover{
    transform:translateY(-3px);

    box-shadow:
        0 14px 35px rgba(20,40,30,.08);
}

.stat-card::after{
    content:"";
    position:absolute;

    width:90px;
    height:90px;

    right:-35px;
    bottom:-35px;

    border-radius:50%;

    background:rgba(31,93,66,.055);
}

.stat-top{
    display:flex;
    align-items:center;
    justify-content:space-between;
}

.stat-icon{
    width:44px;
    height:44px;

    display:flex;
    align-items:center;
    justify-content:center;

    border-radius:13px;

    background:#edf7f1;
    color:#1f5d42;

    font-size:17px;
}

.stat-label{
    margin-top:17px;

    color:#667085;

    font-size:12px;
    font-weight:600;
}

.stat-number{
    margin-top:5px;

    color:#18212b;

    font-size:26px;
    line-height:1;

    font-weight:800;
}


/* ============================================================
   CONTENT GRID
============================================================ */

.dashboard-grid{
    display:grid;
    grid-template-columns:minmax(0,1.45fr) minmax(320px,.8fr);
    gap:20px;
}


/* ============================================================
   PANEL
============================================================ */

.dashboard-panel{
    background:#fff;

    border:1px solid #e9eef2;
    border-radius:18px;

    box-shadow:
        0 8px 28px rgba(20,40,30,.045);

    overflow:hidden;
}

.panel-header{
    display:flex;
    align-items:center;
    justify-content:space-between;

    padding:19px 20px;

    border-bottom:1px solid #edf0f2;
}

.panel-title{
    margin:0;

    color:#17202a;

    font-size:14px;
    font-weight:800;
}

.panel-link{
    color:#1f5d42;

    text-decoration:none;

    font-size:11px;
    font-weight:700;
}

.panel-link:hover{
    text-decoration:underline;
}


/* ============================================================
   TABLE
============================================================ */

.dashboard-table{
    width:100%;
    border-collapse:collapse;
}

.dashboard-table th{
    padding:13px 20px;

    background:#fafcfb;

    color:#8a94a6;

    font-size:10px;
    font-weight:800;

    text-align:left;

    text-transform:uppercase;
    letter-spacing:.5px;
}

.dashboard-table td{
    padding:14px 20px;

    border-top:1px solid #f0f2f4;

    color:#344054;

    font-size:12px;
}

.dashboard-table tbody tr{
    transition:background .18s ease;
}

.dashboard-table tbody tr:hover{
    background:#fbfdfc;
}

.item-name{
    color:#1d2939;
    font-weight:700;
}

.item-email{
    color:#667085;
    font-size:11px;
}

.status{
    display:inline-flex;
    align-items:center;

    padding:5px 9px;

    border-radius:999px;

    font-size:10px;
    font-weight:700;
}

.status.active{
    color:#146c43;
    background:#eaf7ef;
}

.status.inactive{
    color:#b42318;
    background:#fff0ee;
}

.empty-state{
    padding:35px 20px;

    text-align:center;

    color:#98a2b3;

    font-size:12px;
}


/* ============================================================
   QUICK ACTIONS
============================================================ */

.quick-actions{
    padding:20px;
}

.quick-action{
    display:flex;
    align-items:center;
    gap:13px;

    padding:13px;

    margin-bottom:10px;

    border:1px solid #edf0f2;
    border-radius:13px;

    color:#344054;

    text-decoration:none;

    transition:
        background .2s ease,
        transform .2s ease,
        border-color .2s ease;
}

.quick-action:last-child{
    margin-bottom:0;
}

.quick-action:hover{
    background:#f8fbf9;
    border-color:#dcebe2;

    transform:translateX(3px);
}

.quick-icon{
    width:38px;
    height:38px;

    display:flex;
    align-items:center;
    justify-content:center;

    flex-shrink:0;

    border-radius:11px;

    background:#edf7f1;
    color:#1f5d42;
}

.quick-content strong{
    display:block;

    color:#1d2939;

    font-size:12px;
}

.quick-content span{
    display:block;

    margin-top:3px;

    color:#98a2b3;

    font-size:10px;
}


/* ============================================================
   RESPONSIVE
============================================================ */

@media(max-width:1200px){

    .dashboard-stats{
        grid-template-columns:repeat(2,1fr);
    }

    .dashboard-grid{
        grid-template-columns:1fr;
    }

}

@media(max-width:700px){

    .dashboard-header{
        align-items:flex-start;
        flex-direction:column;
    }

    .dashboard-stats{
        grid-template-columns:1fr;
    }

    .dashboard-heading h1{
        font-size:24px;
    }

    .dashboard-table{
        min-width:600px;
    }

    .dashboard-panel{
        overflow-x:auto;
    }

}

</style>


<div class="dashboard-wrapper">

    <!-- ========================================================
         HEADER
    ========================================================= -->

    <div class="dashboard-header">

        <div class="dashboard-heading">

            <h1>
                Dashboard
            </h1>

            <p>
                Welcome back. Manage your Pure Chemical website
                from one place.
            </p>

        </div>

        <div class="dashboard-date">

            <i class="fa-regular fa-calendar"></i>

            <?php
            echo htmlspecialchars(
                date('d M Y')
            );
            ?>

        </div>

    </div>


    <!-- ========================================================
         STATISTICS
    ========================================================= -->

    <div class="dashboard-stats">


        <!-- PRODUCTS -->

        <div class="stat-card">

            <div class="stat-top">

                <div class="stat-icon">
                    <i class="fa-solid fa-box-open"></i>
                </div>

            </div>

            <div class="stat-label">
                Products
            </div>

            <div class="stat-number">
                <?= number_format($stats['products']) ?>
            </div>

        </div>


        <!-- CATEGORIES -->

        <div class="stat-card">

            <div class="stat-top">

                <div class="stat-icon">
                    <i class="fa-solid fa-layer-group"></i>
                </div>

            </div>

            <div class="stat-label">
                Categories
            </div>

            <div class="stat-number">
                <?= number_format($stats['categories']) ?>
            </div>

        </div>


        <!-- INDUSTRIES -->

        <div class="stat-card">

            <div class="stat-top">

                <div class="stat-icon">
                    <i class="fa-solid fa-industry"></i>
                </div>

            </div>

            <div class="stat-label">
                Industries
            </div>

            <div class="stat-number">
                <?= number_format($stats['industries']) ?>
            </div>

        </div>


        <!-- SERVICES -->

        <div class="stat-card">

            <div class="stat-top">

                <div class="stat-icon">
                    <i class="fa-solid fa-gears"></i>
                </div>

            </div>

            <div class="stat-label">
                Services
            </div>

            <div class="stat-number">
                <?= number_format($stats['services']) ?>
            </div>

        </div>

    </div>


    <!-- ========================================================
         MAIN GRID
    ========================================================= -->

    <div class="dashboard-grid">


        <!-- ====================================================
             RECENT ENQUIRIES
        ===================================================== -->

        <div class="dashboard-panel">

            <div class="panel-header">

                <h2 class="panel-title">
                    Recent Enquiries
                </h2>

                <a
                    href="enquiries/"
                    class="panel-link"
                >
                    View All
                </a>

            </div>


            <?php if (!empty($recentEnquiries)): ?>

                <table class="dashboard-table">

                    <thead>

                        <tr>

                            <th>
                                Name
                            </th>

                            <th>
                                Email
                            </th>

                            <th>
                                Date
                            </th>

                        </tr>

                    </thead>

                    <tbody>

                        <?php foreach ($recentEnquiries as $enquiry): ?>

                            <tr>

                                <td>

                                    <div class="item-name">
                                        <?= htmlspecialchars(
                                            (string)($enquiry['name'] ?? 'Unknown')
                                        ) ?>
                                    </div>

                                </td>

                                <td>

                                    <div class="item-email">
                                        <?= htmlspecialchars(
                                            (string)($enquiry['email'] ?? '-')
                                        ) ?>
                                    </div>

                                </td>

                                <td>

                                    <?= !empty($enquiry['created_at'])
                                        ? htmlspecialchars(
                                            date(
                                                'd M Y',
                                                strtotime(
                                                    (string)$enquiry['created_at']
                                                )
                                            )
                                        )
                                        : '-'
                                    ?>

                                </td>

                            </tr>

                        <?php endforeach; ?>

                    </tbody>

                </table>

            <?php else: ?>

                <div class="empty-state">

                    <i class="fa-regular fa-envelope-open"></i>

                    <div style="margin-top:8px;">
                        No enquiries found.
                    </div>

                </div>

            <?php endif; ?>

        </div>


        <!-- ====================================================
             QUICK ACTIONS
        ===================================================== -->

        <div class="dashboard-panel">

            <div class="panel-header">

                <h2 class="panel-title">
                    Quick Actions
                </h2>

            </div>


            <div class="quick-actions">


                <a
                    href="menu.php"
                    class="quick-action"
                >

                    <div class="quick-icon">
                        <i class="fa-solid fa-bars"></i>
                    </div>

                    <div class="quick-content">

                        <strong>
                            Manage Menu
                        </strong>

                        <span>
                            Create and manage website menus
                        </span>

                    </div>

                </a>


                <a
                    href="submenu.php"
                    class="quick-action"
                >

                    <div class="quick-icon">
                        <i class="fa-solid fa-list-tree"></i>
                    </div>

                    <div class="quick-content">

                        <strong>
                            Manage Submenus
                        </strong>

                        <span>
                            Manage menu child items
                        </span>

                    </div>

                </a>


                <a
                    href="products/"
                    class="quick-action"
                >

                    <div class="quick-icon">
                        <i class="fa-solid fa-box"></i>
                    </div>

                    <div class="quick-content">

                        <strong>
                            Products
                        </strong>

                        <span>
                            Add and manage products
                        </span>

                    </div>

                </a>


                <a
                    href="pages/"
                    class="quick-action"
                >

                    <div class="quick-icon">
                        <i class="fa-solid fa-file-lines"></i>
                    </div>

                    <div class="quick-content">

                        <strong>
                            Pages
                        </strong>

                        <span>
                            Manage website pages
                        </span>

                    </div>

                </a>


                <a
                    href="media/"
                    class="quick-action"
                >

                    <div class="quick-icon">
                        <i class="fa-solid fa-photo-film"></i>
                    </div>

                    <div class="quick-content">

                        <strong>
                            Media Library
                        </strong>

                        <span>
                            Manage website media
                        </span>

                    </div>

                </a>

            </div>

        </div>

    </div>

</div>

<?php

/*
|--------------------------------------------------------------------------
| Admin Footer
|--------------------------------------------------------------------------
*/

require_once __DIR__ . '/footer.php';

?>