// استدعاء المكتبات
require('dotenv').config();

const express = require('express');
const cors = require('cors');
const { Pool } = require('pg');
const upload = require('./upload');
// إنشاء التطبيق
const app = express();

// السماح باستقبال JSON
app.use(express.json());

// السماح بالاتصال من الواجهة
app.use(cors());

const path = require('path');
const sharp = require('sharp');
const fs = require('fs');

app.use(
  express.static(
    path.join(__dirname, 'public')
  )
);

// الاتصال بقاعدة البيانات
const pool = new Pool({
  host: process.env.DB_HOST,
  port: process.env.DB_PORT,
  database: process.env.DB_NAME,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
});

app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, '..', 'public', 'index.html'));
});

// اختبار قاعدة البيانات
app.get('/test-db', async (req, res) => {
  try {

    const result = await pool.query('SELECT NOW()');

    res.json({
      success: true,
      time: result.rows[0]
    });

  } catch (error) {

    res.status(500).json({
      success: false,
      error: error.message
    });

  }
});

// إضافة عرض جديد
app.post('/offers', async (req, res) => {

    try {
  
      const {
        title,
        image_url,
        old_price,
        new_price,
        is_featured
      } = req.body;
  
      const result = await pool.query(
        `
        INSERT INTO offers
        (
          title,
          image_url,
          old_price,
          new_price,
          is_featured
        )
        VALUES
        ($1,$2,$3,$4,$5)
        RETURNING *
        `,
        [
          title,
          image_url,
          old_price,
          new_price,
          is_featured
        ]
      );
  
      res.json(result.rows[0]);
  
    } catch (error) {
  
      res.status(500).json({
        error: error.message
      });
  
    }
  
  });


  // جلب جميع العروض
  app.get('/offers', async (req, res) => {
    try {
      const result = await pool.query(`
        SELECT *
        FROM offers
        ORDER BY id DESC
      `);
  
      res.json(result.rows);
    } catch (error) {
      res.status(500).json({
        error: error.message
      });
    }
  });

  app.put('/offers/:id', async (req, res) => {

    try {
  
      const { id } = req.params;
  
      const {
        title,
        image_url,
        old_price,
        new_price,
        is_featured,
        is_active
      } = req.body;
  
      const result = await pool.query(
        `
        UPDATE offers
SET
  title = $1,
  image_url = $2,
  old_price = $3,
  new_price = $4,
  is_featured = $5,
  is_active = $6,
  active_until =
    CASE
      WHEN $6 = true THEN (NOW() AT TIME ZONE 'Asia/Riyadh') + INTERVAL '24 hours'
      ELSE active_until
    END
WHERE id = $7
RETURNING *
        `,
        [
          title,
          image_url,
          old_price,
          new_price,
          is_featured,
          is_active,
          id
        ]
      );
  
      res.json(result.rows[0]);
  
    } catch (error) {
  
      res.status(500).json({
        error: error.message
      });
  
    }
  
  });

  app.delete('/offers/:id', async (req, res) => {

    try {
  
      const { id } = req.params;
  
      await pool.query(
        'DELETE FROM offers WHERE id = $1',
        [id]
      );
  
      res.json({
        success: true
      });
  
    } catch (error) {
  
      res.status(500).json({
        error: error.message
      });
  
    }
  
  });

  // جلب العروض النشطة فقط للمجلة
  app.get('/public-offers', async (req, res) => {
    try {
      const result = await pool.query(`
        SELECT *
FROM offers
WHERE is_active = true
AND (
  active_until IS NULL OR active_until > (NOW() AT TIME ZONE 'Asia/Riyadh')
)
ORDER BY id DESC
      `);
  
      res.json(result.rows);
    } catch (error) {
      res.status(500).json({
        error: error.message
      });
    }
  });


  app.post(
  '/upload-image',
  upload.single('image'),
  async (req, res) => {
    try {
      const originalPath = req.file.path;

      const compressedName =
        'compressed-' +
        Date.now() +
        '.jpg';

      const compressedPath = path.join(
        __dirname,
        '../public/uploads',
        compressedName
      );

      await sharp(originalPath)
        .rotate()
        .resize({
          width: 1000,
          height: 1000,
          fit: 'inside',
          withoutEnlargement: true
        })
        .jpeg({
          quality: 82
        })
        .toFile(compressedPath);

      fs.unlinkSync(originalPath);

      res.json({
        success: true,
        imageUrl: '/uploads/' + compressedName
      });

    } catch (error) {
      res.status(500).json({
        error: error.message
      });
    }
  }
);


  // رفع صورة أو فيديو للسلايدر
app.post(
    '/sliders',
    upload.single('media'),
    async (req, res) => {
  
      try {
  
        const mediaType =
          req.file.mimetype.startsWith('video')
            ? 'video'
            : 'image';
  
        const mediaUrl =
          '/uploads/' + req.file.filename;
  
        const result = await pool.query(
          `
          INSERT INTO sliders
          (
            media_url,
            media_type,
            is_active,
            sort_order
          )
          VALUES
          ($1,$2,true,0)
          RETURNING *
          `,
          [
            mediaUrl,
            mediaType
          ]
        );
  
        res.json(result.rows[0]);
  
      } catch (error) {
  
        res.status(500).json({
          error: error.message
        });
  
      }
  
    }
  );
  
  // جلب عناصر السلايدر
  app.get('/sliders', async (req, res) => {

    try {
  
      const result = await pool.query(
        `
        SELECT *
        FROM sliders
        ORDER BY sort_order ASC, id DESC
        `
      );
  
      res.json(result.rows);
  
    } catch (error) {
  
      res.status(500).json({
        error: error.message
      });
  
    }
  
  });

  app.put('/sliders/:id/toggle', async (req, res) => {

    try {
  
      const { id } = req.params;
  
      const result = await pool.query(
        `
        UPDATE sliders
        SET is_active = NOT is_active
        WHERE id = $1
        RETURNING *
        `,
        [id]
      );
  
      res.json(result.rows[0]);
  
    } catch (error) {
  
      res.status(500).json({
        error: error.message
      });
  
    }
  
  });

  app.delete('/sliders/:id', async (req, res) => {

    try {
  
      const { id } = req.params;
  
      await pool.query(
        'DELETE FROM sliders WHERE id = $1',
        [id]
      );
  
      res.json({
        success: true
      });
  
    } catch (error) {
  
      res.status(500).json({
        error: error.message
      });
  
    }
  
  });


  app.get('/public-sliders', async (req, res) => {

    try {
  
      const result = await pool.query(
        `
        SELECT *
        FROM sliders
        WHERE is_active = true
        ORDER BY sort_order ASC, id DESC
        `
      );
  
      res.json(result.rows);
  
    } catch (error) {
  
      res.status(500).json({
        error: error.message
      });
  
    }
  
  });


  // إضافة فعالية جديدة
app.post('/events', async (req, res) => {
    try {
      const {
        title,
        image_url,
        start_date,
        end_date,
        is_active
      } = req.body;
  
      const result = await pool.query(
        `
        INSERT INTO events
        (
          title,
          image_url,
          start_date,
          end_date,
          is_active
        )
        VALUES
        ($1,$2,$3,$4,$5)
        RETURNING *
        `,
        [title, image_url, start_date, end_date, is_active]
      );
  
      res.json(result.rows[0]);
    } catch (error) {
      res.status(500).json({
        error: error.message
      });
    }
  });
  
  // جلب كل الفعاليات للوحة التحكم
  app.get('/events', async (req, res) => {
    try {
      const result = await pool.query(`
        SELECT *
        FROM events
        ORDER BY id DESC
      `);
  
      res.json(result.rows);
    } catch (error) {
      res.status(500).json({
        error: error.message
      });
    }
  });
  
  // جلب الفعاليات النشطة للمجلة
  app.get("/public-events", async (req, res) => {
  try {
    const result = await pool.query(`
      SELECT *
      FROM events
      WHERE is_active = true
      AND (
        start_date IS NULL OR start_date <= CURRENT_DATE
      )
      AND (
        end_date IS NULL OR end_date >= CURRENT_DATE
      )
     ORDER BY end_date DESC NULLS LAST, id DESC
    `);

    res.json(result.rows);
  } catch (error) {
    res.status(500).json({
      error: error.message,
    });
  }
});


  app.put("/events/:id/toggle", async (req, res) => {
    try {
      const { id } = req.params;
  
      const result = await pool.query(
        `
        UPDATE events
        SET is_active = NOT is_active
        WHERE id = $1
        RETURNING *
        `,
        [id]
      );
  
      res.json(result.rows[0]);
    } catch (error) {
      res.status(500).json({
        error: error.message,
      });
    }
  });
  
  app.delete("/events/:id", async (req, res) => {
    try {
      const { id } = req.params;
  
      await pool.query(
        "DELETE FROM events WHERE id = $1",
        [id]
      );
  
      res.json({
        success: true,
      });
    } catch (error) {
      res.status(500).json({
        error: error.message,
      });
    }
  });

  app.put("/events/:id", async (req, res) => {
    try {
      const { id } = req.params;
  
      const {
        title,
        image_url,
        start_date,
        end_date,
        is_active
      } = req.body;
  
      const result = await pool.query(
        `
        UPDATE events
        SET
          title = $1,
          image_url = $2,
          start_date = $3,
          end_date = $4,
          is_active = $5
        WHERE id = $6
        RETURNING *
        `,
        [
          title,
          image_url,
          start_date,
          end_date,
          is_active,
          id
        ]
      );
  
      res.json(result.rows[0]);
    } catch (error) {
      res.status(500).json({
        error: error.message,
      });
    }
  });

app.post("/admin-login", async (req, res) => {
  try {
    const { username, password } = req.body;

    const result = await pool.query(
      `
      SELECT id, username
      FROM admins
      WHERE username = $1
      AND is_active = true
      AND password_hash = crypt($2, password_hash)
      LIMIT 1
      `,
      [username, password]
    );

    if (!result.rows.length) {
      return res.status(401).json({
        success: false,
        message: "بيانات الدخول غير صحيحة"
      });
    }

    res.json({
      success: true,
      username: result.rows[0].username
    });

  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.get("/settings", async (req, res) => {
    try {
      const result = await pool.query(
        `
        SELECT *
        FROM settings
        LIMIT 1
        `
      );
  
      res.json(result.rows[0]);
    } catch (error) {
      res.status(500).json({
        error: error.message,
      });
    }
  });
  
  app.put("/settings", async (req, res) => {
    try {
      const {
        install_icon_color,
        share_icon_color,
        location_icon_color,
        magazine_title,
        website_url,
        google_review_url,
        primary_color,
        secondary_color,
        background_color,
        header_color,
        title_color,
        price_color,
        button_color,
        discount_color,
        show_slider,
        show_events,
        show_featured,
        show_daily,
        show_update_time,
        slider_image_seconds,
        product_title_color,
        old_price_color,
        magazine_title_color,
        featured_card_color,
        daily_card_color

      } = req.body;
  
      const result = await pool.query(
  `
  UPDATE settings
  SET
    magazine_title = $1,
    website_url = $2,
    google_review_url = $3,
    primary_color = $4,
    secondary_color = $5,
    background_color = $6,
    header_color = $7,
    title_color = $8,
    price_color = $9,
    button_color = $10,
    discount_color = $11,
    show_slider = $12,
    show_events = $13,
    show_featured = $14,
    show_daily = $15,
    show_update_time = $16,
    slider_image_seconds = $17,
    install_icon_color = $18,
    share_icon_color = $19,
    location_icon_color = $20,
    product_title_color = $21,
    old_price_color = $22,
    magazine_title_color = $23,
    featured_card_color = $24,
    daily_card_color = $25
  WHERE id = 1
  RETURNING *
  `,
  [
    magazine_title,
    website_url,
    google_review_url,
    primary_color,
    secondary_color,
    background_color,
    header_color,
    title_color,
    price_color,
    button_color,
    discount_color,
    show_slider,
    show_events,
    show_featured,
    show_daily,
    show_update_time,
    slider_image_seconds,
    install_icon_color,
    share_icon_color,
    location_icon_color,
    product_title_color,
    old_price_color,
    magazine_title_color,
    featured_card_color,
    daily_card_color
  ]
);
  
      res.json(result.rows[0]);
    } catch (error) {
      res.status(500).json({ error: error.message });
    }
  });

  setInterval(async () => {
  try {
    await pool.query(`
      UPDATE offers
      SET is_active = false
      WHERE is_active = true
      AND active_until IS NOT NULL
      AND active_until <= (NOW() AT TIME ZONE 'Asia/Riyadh')
    `);
  } catch (error) {
    console.log("Auto hide offers error:", error.message);
  }
}, 60 * 1000);

  // تشغيل السيرفر
app.listen(process.env.PORT, () => {

  console.log(
    `Server Running On Port ${process.env.PORT}`
  );

});