<?php
session_start();
require_once '../config.php';

if (!isset($_SESSION['user_id']) || !isset($_SESSION['role']) || $_SESSION['role'] !== 'medical_representative') {
    die("Access Denied");
}

function e($v) {
    return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8');
}

$mr_id = (int)$_SESSION['user_id'];
$message = "";

// ================= ADD VISIT =================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $pharmacy_id = (int)($_POST['pharmacy_id'] ?? 0);
    $status      = trim($_POST['visit_status'] ?? 'visited');
    $datetime    = trim($_POST['visit_datetime'] ?? '');
    $remarks     = trim($_POST['remarks'] ?? '');

    if ($pharmacy_id <= 0 || $datetime === '') {
        $message = "Please select pharmacy and visit date/time.";
    } else {
        $stmt = $conn->prepare("
            INSERT INTO pharmacy_visits (pharmacy_id, mr_id, visit_status, visit_date, remarks)
            VALUES (?, ?, ?, ?, ?)
        ");

        if ($stmt) {
            $stmt->bind_param("iisss", $pharmacy_id, $mr_id, $status, $datetime, $remarks);

            if ($stmt->execute()) {
                header("Location: pharmacy_visit.php?success=1");
                exit;
            } else {
                $message = "Failed to save pharmacy visit.";
            }
            $stmt->close();
        } else {
            $message = "Database prepare failed.";
        }
    }
}

if (isset($_GET['success'])) {
    $message = "Pharmacy visit saved successfully.";
}

// ================= GET PHARMACIES =================
$pharmacies = $conn->query("SELECT id, pharmacy_name FROM pharmacies ORDER BY pharmacy_name ASC");

// ================= SEARCH =================
$search = $_GET['search'] ?? '';

$sql = "
    SELECT pv.*, p.pharmacy_name
    FROM pharmacy_visits pv
    JOIN pharmacies p ON pv.pharmacy_id = p.id
    WHERE pv.mr_id = ?
";

if (!empty($search)) {
    $sql .= " AND p.pharmacy_name LIKE ?";
}

$sql .= " ORDER BY pv.visit_date DESC";

$stmt = $conn->prepare($sql);

if (!empty($search)) {
    $search_param = "%$search%";
    $stmt->bind_param("is", $mr_id, $search_param);
} else {
    $stmt->bind_param("i", $mr_id);
}

$stmt->execute();
$result = $stmt->get_result();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pharmacy Visits</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        * { box-sizing: border-box; }

        body {
            margin: 0;
            padding: 0;
            font-family: Arial, sans-serif;
            background: #f4f6f9;
            color: #2d3436;
        }

        .page-wrapper {
            display: flex;
        }

        .main-content {
            flex: 1;
            padding: 0px 20px 20px;
            margin-left: 260px;
            margin-top: 0;
        }

        .container {
            max-width: 1100px;
            margin: auto;
            padding-top: 0;
        }

        .page-header {
            color: #000;
            border-radius: 16px;
            margin: 0 0 12px;
            padding: 0px 20px 8px;
        }

        .page-header h2 {
            margin: 0;
            font-size: 22px;
        }

        .page-header p {
            margin: 6px 0 0;
            opacity: 0.9;
            font-size: 13px;
        }

        .message {
            padding: 14px 16px;
            border-radius: 12px;
            margin-bottom: 18px;
            font-weight: 600;
        }

        .message.success {
            background: #e8fff1;
            color: #166534;
            border: 1px solid #bbf7d0;
        }

        .message.error {
            background: #fff1f2;
            color: #991b1b;
            border: 1px solid #fecdd3;
        }

        .card {
            background: #fff;
            border-radius: 14px;
            padding: 16px;
            border: 1px solid #e2e8f0;
            box-shadow: 0 6px 20px rgba(0,0,0,0.08);
            margin-bottom: 14px;
        }

        .form-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 12px;
        }

        .field-group {
            display: flex;
            flex-direction: column;
        }

        .field-group.full {
            grid-column: 1 / -1;
        }

        label {
            font-size: 12px;
            font-weight: 600;
            margin-bottom: 8px;
            color: #374151;
        }

        input, select, textarea {
            width: 100%;
            padding: 9px 10px;
            border: 1px solid #d1d5db;
            border-radius: 10px;
            outline: none;
            background: #fff;
            font-size: 13px;
            transition: 0.2s ease;
        }

        input:focus, select:focus, textarea:focus {
            border-color: #334155;
            box-shadow: 0 0 0 3px rgba(37,99,235,0.12);
        }

        textarea {
            resize: vertical;
            min-height: 90px;
        }

        .actions {
            display: flex;
            gap: 12px;
            margin-top: 8px;
        }

        .btn {
            border: none;
            padding: 8px 14px;
            font-size: 13px;
            border-radius: 10px;
            font-weight: 700;
            cursor: pointer;
            transition: 0.2s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }

        .btn-primary {
            background: #334155;
            color: #fff;
        }

        .btn-primary:hover {
            background: #1f2937;
        }

        .btn-secondary {
            background: #e5e7eb;
            color: #111827;
        }

        .btn-secondary:hover {
            background: #d1d5db;
        }

        .section-title {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 16px;
            gap: 12px;
        }

        .section-title h3 {
            margin: 0;
            font-size: 20px;
            color: #111827;
        }

        .search-box {
            display: flex;
            gap: 12px;
            align-items: center;
            margin-bottom: 0;
            width: 100%;
        }

        .search-box input {
            padding: 9px 10px;
            font-size: 13px;
            flex: 1;
        }

        .table-card {
            overflow: hidden;
        }

        .table-responsive {
            width: 100%;
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            min-width: 800px;
        }

        th, td {
            color: #111827;
            padding: 14px 12px;
            border-bottom: 1px solid #e5e7eb;
            text-align: left;
            vertical-align: top;
        }

        th {
            background-color: #374155;
            color: #fff;
            font-size: 13px;
            font-weight: 800;
        }

        tr:hover td {
            background: #fafafa;
        }

        .status {
            display: inline-block;
            padding: 7px 12px;
            border-radius: 999px;
            font-size: 13px;
            font-weight: 700;
        }

        .visited {
            color: #047857;
            background: #ecfdf5;
        }

        .not-visited {
            color: #b45309;
            background: #fff7ed;
        }

        .empty-state {
            padding: 24px;
            text-align: center;
            color: #6b7280;
        }

        .title-wrap {
            display: flex;
            align-items: center;
            gap: 14px;
        }

        .title-icon {
            width: 46px;
            height: 46px;
            border-radius: 12px;
            background: #334155;
            color: #fff;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
        }

        @media (max-width: 900px) {
            .main-content {
                margin-left: 0;
                margin-top: 0;
                padding: 16px;
            }

            .form-grid {
                grid-template-columns: 1fr;
            }

            .section-title {
                flex-direction: column;
                align-items: stretch;
            }

            .search-box {
                flex-direction: column;
                align-items: stretch;
            }

            .actions {
                flex-direction: column;
            }
        }

        @media (max-width: 768px) {
            .main-content {
                margin-left: 0 !important;
                padding: 12px;
            }

            .container {
                max-width: 100%;
                padding: 0;
            }

            .title-wrap {
                align-items: flex-start;
                gap: 10px;
            }

            .title-icon {
                width: 40px;
                height: 40px;
                font-size: 16px;
            }

            .page-header h2 {
                font-size: 18px;
            }

            .page-header p {
                font-size: 12px;
            }

            .form-grid {
                grid-template-columns: 1fr;
                gap: 10px;
            }

            .field-group label {
                font-size: 12px;
                margin-bottom: 4px;
            }

            input, select, textarea {
                font-size: 13px;
                padding: 10px;
            }

            textarea {
                min-height: 70px;
            }

            .actions {
                flex-direction: column;
                gap: 8px;
            }

            .btn {
                width: 100%;
                justify-content: center;
                height: 42px;
            }

            .search-box {
                flex-direction: column;
                gap: 8px;
            }

            .search-box input {
                width: 100%;
            }

            table {
                min-width: 100% !important;
            }

            table thead {
                display: none;
            }

            table tbody tr {
                display: block;
                margin-bottom: 12px;
                background: #f8fafc;
                border: 1px solid #e2e8f0;
                border-radius: 12px;
                padding: 10px;
            }

            table tbody td {
                display: flex;
                justify-content: space-between;
                padding: 6px 0;
                border: none;
                font-size: 13px;
            }

            table tbody td::before {
                content: attr(data-label);
                font-weight: 600;
                color: #64748b;
            }
        }
    </style>
</head>
<body>

<?php include 'salesexecutivesidebar.php'; ?>
<?php include '../header.php'; ?>

<div class="page-wrapper">
    <div class="main-content">
        <div class="container">

            <div class="page-header">
                <div class="title-wrap">
                    <div class="title-icon">
                        <i class="fa-solid fa-prescription-bottle-medical"></i>
                    </div>
                    <div>
                        <h2>Pharmacy Visit</h2>
                        <p>Record pharmacy visit status, date & time, and remarks.</p>
                    </div>
                </div>
            </div>

            <?php if (!empty($message)): ?>
                <div class="message <?php echo isset($_GET['success']) ? 'success' : 'error'; ?>">
                    <?php echo e($message); ?>
                </div>
            <?php endif; ?>

            <div class="card">
                <div class="section-title">
                    <h3>Add Visit</h3>
                </div>

                <form method="POST">
                    <div class="form-grid">
                        <div class="field-group">
                            <label>Pharmacy</label>
                            <select name="pharmacy_id" required>
                                <option value="">Select Pharmacy</option>
                                <?php while ($p = $pharmacies->fetch_assoc()): ?>
                                    <option value="<?php echo (int)$p['id']; ?>">
                                        <?php echo e($p['pharmacy_name']); ?>
                                    </option>
                                <?php endwhile; ?>
                            </select>
                        </div>

                        <div class="field-group">
                            <label>Visit Status</label>
                            <select name="visit_status" required>
                                <option value="visited">Visited</option>
                                <option value="not_visited">Not Visited</option>
                            </select>
                        </div>

                        <div class="field-group">
                            <label>Visit Date & Time</label>
                            <input type="datetime-local" name="visit_datetime" required>
                        </div>

                        <div class="field-group full">
                            <label>Remarks</label>
                            <textarea name="remarks" placeholder="Write visit notes here..."></textarea>
                        </div>
                    </div>

                    <div class="actions">
                        <button type="submit" class="btn btn-primary">Save Visit</button>
                        <a href="pharmacy_visit.php" class="btn btn-secondary">Reset</a>
                    </div>
                </form>
            </div>

            <div class="card table-card">
                <div class="section-title">
                    <form method="GET" class="search-box">
                        <input type="text" name="search" placeholder="Search pharmacy..." value="<?php echo e($search); ?>">
                        <button type="submit" class="btn btn-primary">Search</button>
                    </form>
                </div>

                <div class="table-responsive">
                    <table>
                        <thead>
                            <tr>
                                <th>Pharmacy Name</th>
                                <th>Status</th>
                                <th>Visit Date & Time</th>
                                <th>Remarks</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($result->num_rows > 0): ?>
                                <?php while ($row = $result->fetch_assoc()): ?>
                                    <tr>
                                        <td data-label="Pharmacy"><?php echo e($row['pharmacy_name']); ?></td>

                                        <td data-label="Status">
                                            <span class="status <?php echo $row['visit_status'] === 'visited' ? 'visited' : 'not-visited'; ?>">
                                                <?php echo ucfirst(str_replace('_', ' ', $row['visit_status'])); ?>
                                            </span>
                                        </td>

                                        <td data-label="Date">
                                            <?php echo date("d M Y h:i A", strtotime($row['visit_date'])); ?>
                                        </td>

                                        <td data-label="Remarks">
                                            <?php echo e($row['remarks'] ?? ''); ?>
                                        </td>
                                    </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="4">
                                        <div class="empty-state">No visit records found.</div>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

        </div>
    </div>
</div>

</body>
</html>